Haskell使用Eq =>在函数定义中

时间:2012-09-08 12:31:17

标签: haskell

我有一个包含抽象数据类型作为参数的函数。为了让我能够将我使用的抽象数据类型等同于:

myfunction:: Eq x=> [x]->[x]->[x]

因此它包含两个x列表,并输出[x]

列表

然而,当我从另一个函数调用它时:

anotherfunction::[x] -> [x] -> [x]
anotherfunction a b = myfunction a b

它说

  

使用myfunction时没有(Eq x)的实例   表达myfunction a b

但是,如果我从控制台调用myfunction,使用这两个参数就可以了。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:10)

Eq

类型中使用anotherfunction
anotherfunction::Eq x => [x] -> [x] -> [x]
anotherfunction a b = myfunction a b

myfunction仅适用于Eq类中的类型。但是您目前对anotherfunction的定义声称它可以适用于任何类型。如果您使用anotherfunction类中的类型调用Eq,则会导致问题 - 它将无法调用myfunction。< / p>

答案 1 :(得分:2)

myfunction:: Eq x=> [x]->[x]->[x]

这里x必须有一个Eq类的实例声明。

anotherfunction::[x] -> [x] -> [x]
anotherfunction a b = myfunction a b

此处myfunction假定ab的类型属于Eq类,但anotherfunction的类型不构成此类约束。

正确的方法是在anotherfunction中指定此约束。

anotherfunction:: Eq x => [x] -> [x] -> [x]
anotherfunction a b = myfunction a b

如果您有任何疑惑,最简单的方法是不向anotherfunction提供任何类型 并在ghci中加载该文件,并查看为anotherfunction推断的类型。

> :t anotherfunction 
anotherfunction :: Eq x => [x] -> [x] -> [x]

ghc将推断出最通用的类​​型,因此如果您希望类型更具体,那么最好为x提供显式类型。喜欢

anotherfunction :: [Int] -> [Int] -> [Int]

Eq Int实例已定义,因此您不会收到任何错误。因此,如果将多态类型x分配给任何特定类型,则只需确保它具有受约束类的实例。

相关问题