I'm trying to check for equality in a haskell application, which takes in an xs of type [a], as so:
myCompare :: Int -> Int -> [a] -> Int
myCompare pointer x xs = if pointer < length xs
then if xs !! pointer == xs !! (pointer+1)
....
However, Haskell has run into an issue where it cannot carry out a comparison between items in the xs array, due to the possibility of them being of differing types.
The error being returned is:
No instance for (Eq a) arising from a use of ‘==’
Possible fix:
add (Eq a) to the context of
the type signature for myCompare :: Int -> Int -> [a] -> Int
I'm new to types, and am unsure on how I can cast this - would someone be able to lend me a hand on this?
Just do what the compiler tells you to: add
Eq
constraint to your function.When you write
a
, you tell the compiler that the function can operate on any type; in other words, that means you don't expect anything from the type.Comparing two values of a particular type isn't a given; it's provided by the
Eq
typeclass. While most ADTs can simply deriveEq
to get that instance, you still need to ensure that the type, values of which you're going to compare, actually has that instance, and that's precisely what the constraint is doing.