[英]Haskell using Eq=> in function definitions
I have a function which contains an abstract data type as a parameter. 我有一个包含抽象数据类型作为参数的函数。 In order for me to be able to equate this abstract data type I used:
为了使我能够等同于此抽象数据类型,我使用了:
myfunction:: Eq x=> [x]->[x]->[x]
So it takes in two lists of x, and outputs a list of [x] 因此,它接受x的两个列表,并输出[x]的列表
However, when I call it from another function: 但是,当我从另一个函数调用它时:
anotherfunction::[x] -> [x] -> [x]
anotherfunction a b = myfunction a b
it says 它说
No instance for (Eq x) arising from a use of myfunction, in the expression myfunction ab
在表达式myfunction ab中没有因使用myfunction而引起的(Eq x)实例
However, if I call myfunction from the console, with the two arguments it works fine. 但是,如果我从控制台调用myfunction,则使用两个参数可以正常工作。
How do I solve this? 我该如何解决?
Use Eq
in the type of anotherfunction
. 在
anotherfunction
类型中使用Eq
。
anotherfunction::Eq x => [x] -> [x] -> [x]
anotherfunction a b = myfunction a b
myfunction
works only with types that are in the Eq
class. myfunction
仅适用于Eq
类中的类型。 But your current definition of anotherfunction
claims it can work with any type. 但是您当前对
anotherfunction
定义声称它可以与任何类型一起使用。 This would cause a problem if you called anotherfunction
with a type that is not in the Eq
class - it wouldn't be able to call myfunction
. 如果您使用不在
Eq
类中的类型调用了anotherfunction
,则将导致问题-无法调用myfunction
。
myfunction:: Eq x=> [x]->[x]->[x]
Here x has to have an instance declaration for Eq class. 在此,x必须具有Eq类的实例声明。
anotherfunction::[x] -> [x] -> [x]
anotherfunction a b = myfunction a b
Here myfunction
assumes type of a
and b
to belong to Eq
class, but the type of anotherfunction
makes no such constraint. 在这里,
myfunction
假定a
和b
类型属于Eq
类,但是anotherfunction
的类型没有这种约束。
The correct way would be to specify this constraint in anotherfunction
also. 正确的方法是还要在
anotherfunction
指定此约束。
anotherfunction:: Eq x => [x] -> [x] -> [x]
anotherfunction a b = myfunction a b
If you have any confusion, the easiest way would be not to give any type to anotherfunction
and load the file in ghci and see what type is inferred for anotherfunction
. 如果您有任何困惑,最简单的方法是不将其他
anotherfunction
任何类型,而将文件加载到ghci中,然后查看为anotherfunction
推断出的anotherfunction
。
> :t anotherfunction
anotherfunction :: Eq x => [x] -> [x] -> [x]
ghc will infer the most generic type so if you want type to be more specific then it is better to give explicit type for x. ghc会推断出最通用的类型,因此,如果您希望类型更具体,则最好为x提供显式类型。 Like
喜欢
anotherfunction :: [Int] -> [Int] -> [Int]
Here Eq
instance for Int
is already defined so you don't get any error. 这里已经定义了
Int
Eq
实例,因此不会出现任何错误。 So If you assign the polymorphic type x
to any specific type then you just need to make sure it has the instances for constrained classes. 因此,如果将多态类型
x
分配给任何特定类型,则只需要确保它具有约束类的实例即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.