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]
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
However, if I call myfunction from the console, with the two arguments it works fine.
How do I solve this?
Use Eq
in the type of anotherfunction
.
anotherfunction::Eq x => [x] -> [x] -> [x]
anotherfunction a b = myfunction a b
myfunction
works only with types that are in the Eq
class. But your current definition of anotherfunction
claims it can work with any type. 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
.
myfunction:: Eq x=> [x]->[x]->[x]
Here x has to have an instance declaration for Eq class.
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.
The correct way would be to specify this constraint in anotherfunction
also.
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
.
> :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. Like
anotherfunction :: [Int] -> [Int] -> [Int]
Here Eq
instance for Int
is already defined so you don't get any error. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.