键入类,实例和包装器

时间:2015-06-06 08:16:52

标签: typeclass purescript

有人可以向我解释为什么这个(版本1)编译而下面的版本(版本2)没有编译。

-- version 1 (compiles)
module Chapter2 where

import Debug.Trace

data Wrapper a = Wrapper a
instance showWrapper :: (Show a) => Show (Wrapper a) where
    show (Wrapper w) = "Wrapper ( " ++ (show w) ++ " )"

foo :: Number -> Number -> Number -> Number
foo a b c = a + b + c
foo1 = foo 2
foo2 = foo 1 2

class ExecFn a where
    exec :: a -> Number

instance execFn1 :: ExecFn (Number -> Number -> Number) where
    exec a = 99

main = do
    let x = exec foo1
    trace "Hello"

这不编译

-- Version 2 (does not compile)
module Chapter2 where

import Debug.Trace

data Wrapper a = Wrapper a
instance showWrapper :: (Show a) => Show (Wrapper a) where
    show (Wrapper w) = "Wrapper ( " ++ (show w) ++ " )"

foo :: Number -> Number -> Number -> Number
foo a b c = a + b + c
foo1 = foo 2
foo2 = foo 1 2

class ExecFn a b where
    exec :: a -> Wrapper b

instance execFn1 :: ExecFn (Number -> Number -> Number) Number where
    exec a = Wrapper 99

main = do
    let x = exec foo1
    trace "Hello"    

并给我这个错误

Error at src/Chapter2.purs line 3, column 1 - line 5, column 1:
  No instance found for Chapter2.ExecFn (Prim.Number -> Prim.Number -> Prim.Number) u8735

那么如何制作与我的版本2类似的版本,以便将结果放入包装器中?

1 个答案:

答案 0 :(得分:1)

x的类型不受约束,这就是错误消息中出现未知类型变量的原因。在搜索类型类实例时,psc不会尝试实例化类型变量。当使用多参数类型类而没有像函数依赖性这样的东西来帮助消除歧义类型时(例如)purescript-transformers具有相同的问题),这有时会成为一个问题。目前,您需要添加类型签名,或使用x以消除类型b的歧义。

因此,如果您为let

添加预期类型
let x = exec foo1 :: Wrapper Number

这应该有帮助