Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeclass in haskell

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?

like image 759
shashydhar Avatar asked Dec 07 '22 10:12

shashydhar


1 Answers

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.)

like image 55
dave4420 Avatar answered Dec 09 '22 14:12

dave4420