Total newbie here, struggling.
I’m trying to define a type class for sets. For this case it would only require the definition of ‘exists’. ‘exists’ would take a set and function on a set item, and return
a boolean. How can I define that in Haskell?
Is the following even in the right direction? So there is the type class definition and an
implementation of set with list, for which ‘exists’ returns true for now..
-- Set.hs --
class Set a b where
exists :: a -> (b -> Bool) -> Bool
-- ListSet.hs --
instance Set ListSet a where
exists a f = True
—
(result: Too many parameters for class `Set’)
You can do it this way, with enough extensions. At the very least, you’ll need multiple-parameter type classes. However, it will be very annoying to use: you’ll need to specify explicit type signatures all over the place. One way to fix it is to introduce a functional dependency (using another extension):
This says that if you know the type of the set, you know the type of the elements, too. However, there’s a simpler way that works without any extensions:
Here, the type class ranges over higher-kinded types, which is a neat trick and hard to come up with on your own if you’ve never seen it before!