2
votes

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:

enter image description here

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!

1
Coupla suggestions: The 'official' version of the book is out of date. This fork is the most up-to-date: github.com/dwhitney/purescript-book . Also, PureScript syntax is so similar to Haskell that I've found it easy to use Haskell books to learn quite a lot of PureScript. I found Haskell Programming From First Principles to be very thorough, and I solved most of the exercises in PureScript.tex

1 Answers

6
votes

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.