I have a class defined like this, so that foo
takes a generic type and returns an Integer:
class Foo a where
foo :: a -> Integer
and a couple of instances defined so it will work with Bool
and Char
types:
instance Foo Bool where
foo _ = 10
instance Foo Char where
foo _ = 20
If I now want to add an instance for a list with a generic type, I would want to do something like this:
instance Foo [a] where
foo (t:ts) = (foo t) + (foo ts)
However, this is wrong. From my current understanding, I would want to assume that Haskell infers the types and does something like this:
foo [False,True] -> foo False + foo True -> 10 + 10 = 20
I've looked at several books and read about polymorphism and typeclasses, including Learn You a Haskell For Great Good! but still can't wrap my head around how to solve this?
data AnyFoo = forall a. Foo a => AnyFoo a
and an instance for it :) – Bartek Banachewicz