繁体   English   中英

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

[英]Haskell using Eq=> in function definitions

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

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

因此,它接受x的两个列表,并输出[x]的列表

但是,当我从另一个函数调用它时:

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

它说

在表达式myfunction ab中没有因使用myfunction而引起的(Eq x)实例

但是,如果我从控制台调用myfunction,则使用两个参数可以正常工作。

我该如何解决?

anotherfunction类型中使用Eq

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

myfunction仅适用于Eq类中的类型。 但是您当前对anotherfunction定义声称它可以与任何类型一起使用。 如果您使用不在 Eq类中的类型调用了anotherfunction ,则将导致问题-无法调用myfunction

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推断出的anotherfunction

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

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

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

这里已经定义了Int Eq实例,因此不会出现任何错误。 因此,如果将多态类型x分配给任何特定类型,则只需要确保它具有约束类的实例即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM