I'm currently learning Purescript by reading the Purescript by Example book (so far one of the only resources I've found that covers the language extensively).
I'm trying to implement the exercises in section 6.7 (Instance Dependencies), and I can't get my head around the following compiler error:
I've implemented the Semigroup and Eq instances for a data type data NonEmpty a = NonEmpty a (Array a)
as follows:
instance eqNonEmpty :: Eq a => Eq (NonEmpty a) where
eq (NonEmpty h1 t1) (NonEmpty h2 t2) = h1 == h2 && t1 == t2
instance semigroupNonEmpty :: Semigroup (NonEmpty a) where
append (NonEmpty h1 t1) (NonEmpty h2 t2) = NonEmpty h1 (t1 <> [h2] <> t2)
But when I try to implement the Functor instance the same way I get the error above. What seems to work is this:
instance functorNonEmpty :: Functor NonEmpty where
map f (NonEmpty h t) = NonEmpty (f h) (map f t)
Now, why is that? I can't figure it out. Thanks!
That's just how the Functor
class is defined: it applies to types that take a parameter. So, for example, the Functor
class would apply to Maybe
and to List
, but wouldn't apply to Int
or to String
, and equally wouldn't apply to Maybe Int
or List String
.
The type NonEmpty
does take a parameter, because that's how it is defined:
data NonEmpty a = ...
But a type NonEmpty a
does not take a parameter, regardless of what a
might be.
The classes Eq
and Semigroup
, on the other hand, expect a type without any parameters. So these classes can apply to Int
, String
, Maybe Boolean
, and any other type without parameters, including NonEmpty a
, regardless of what a
might be.