I'm extremely new to haskell and was trying to implement a small and a simple function that takes two strings and tells me the number of same characters at the same location.
ed :: (Integral b) => [a] -> [a] -> b
ed _ [] = 0
ed [] _ = 0
ed [] [] = 0
ed (x:xs) (y:ys)
| x == y = 1 + ed xs ys
| otherwise = ed xs ys
this doesn't run because my typeclass definition is wrong. I have two strings and need to return an integer and hence the typeclass definition I have written above. Is there something else I need to do?
The type signature should be
ed :: (Eq a, Integral b) => [a] -> [a] -> b
This is because your definition of ed
includes the expression x == y
. x
and y
both have type a
; to be able to test them for equality, this type must implement the Eq
typeclass, which provides the ==
and /=
operators.
The error message you got would have included something like this:
Could not deduce (Eq a) arising from a use of `==' from the context (Integral b) bound by the type signature for ed :: Integral b => [a] -> [a] -> b at /home/dave/tmp/so.hs:(2,1)-(5,26) Possible fix: add (Eq a) to the context of the type signature for ed :: Integral b => [a] -> [a] -> b
which was trying to tell you this.
(Btw, your code doesn't handle the case when when the strings have different lengths.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With