For this piece of haskell code:
isIn :: (Eq a) => [a] -> [a] -> Bool
needle `isIn` haystack = any (needle `isPrefixOf`) (tails haystack)
This is a function definition I believe. How do I understand what the input arguments are and what the return type is?
For example: what is (Eq a)?
Eqis what’s called a typeclass. It declares a few functions, in this case==and friends, and we can make instances of that typeclass which provide definitions for==and others.This means that when we have something that’s an instance of the
Eqtypeclass, we know we can use==on it.The trick here is that in our function, we need to have types which make it possible to check that they’re equal. If we just had
[a] -> [a] -> Boolthen we’d be in trouble because we’d have just promised that our implementation works on things without an==operator which it doesn’t.Because of this we use the
=>which adds context to our function definition. It says something like “This will work for anyaas long asais an instance of theEqtypeclass”. That way, we can use==safely and know that all our argument types will implement it appropriately.Quick Illustration
This is an error:
but this works because we specify
ais an instance ofEq