Typeclass in haskell

I am extremely new to haskell and tried to implement a small and simple function that takes two lines and tells me the number of identical characters in one place.

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 fails because my definition of cool code is wrong. I have two lines, and I need to return an integer, and therefore the style definition that I wrote above. Is there anything else I need to do?

+4
source share
2 answers

Type signature must 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 of type a ; in order to be able to test for equality, this type must implement the Eq , which provides the == and /= operators.

The error message you received would include 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 

who tried to tell you this.

(Btw, your code does not handle the case when the lines have different lengths.)

+11
source

Due to x == y, you need to add an Eq type constraint:

 ed :: (Integral b, Eq a) => [a] -> [a] -> b 

You can comment on the type signature, load your module into ghci and let it understand the type signature:

 Main> :t ed ed :: (Eq a1, Num a) => [a1] -> [a1] -> a 
+4
source

All Articles