imperfectgrist
imperfectgrist

Reputation: 661

How do I use foldrDefault and foldlDefault with my foldMap?

I'm trying to complete Exercise 5 from section 6.7 of Phil Freeman's PureScript book. The exercise wants me to write a Foldable instance for the following type.

data NonEmpty a = NonEmpty a (Array a)

I've written this instance by implementing foldMap.

instance foldableNonEmpty :: Foldable a => Foldable NonEmpty where
  foldMap :: forall a m. Monoid m => (a -> m) -> NonEmpty a -> m
  foldMap f (NonEmpty x xs) = (f x) <> (foldMap f xs)

  foldr :: forall a b. (a -> b -> b) -> b -> NonEmpty a -> b
  foldr f = foldrDefault f

  foldl f = foldlDefault f

But that generates the following error.

Error found:
in module Data.Hashable
at src/Data/Hashable.purs line 110, column 11 - line 110, column 23

  No type class instance was found for

    Data.Foldable.Foldable t2

  The instance head contains unknown type variables. Consider adding a type annotation.

while checking that type forall f a b. Foldable f => (a -> b -> b) -> b -> f a -> b
  is at least as general as type (a0 -> b1 -> b1) -> b1 -> NonEmpty a0 -> b1
while checking that expression foldrDefault
  has type (a0 -> b1 -> b1) -> b1 -> NonEmpty a0 -> b1
in value declaration foldableNonEmpty

where b1 is a rigid type variable
        bound at line 110, column 11 - line 110, column 23
      a0 is a rigid type variable
        bound at line 110, column 11 - line 110, column 23
      t2 is an unknown type

I think I'm getting the error because foldr = foldrDefault implies to the compiler that NonEmpty is already foldable when that's what I'm trying to instance, but then I have no idea how to use the default fold implementations. Any help would be greatly appreciated.

Upvotes: 0

Views: 155

Answers (1)

Brenton Alker
Brenton Alker

Reputation: 9082

I don't think it's actually a problem with your use of the defaults. You seem to have added an unnecessary Foldable a constraint on your instance which I don't think you need. So your instance can be:

instance foldableNonEmpty :: Foldable NonEmpty where

Once you remove that, I think the rest is right!

I tested in the try.purescript.org editor here: http://try.purescript.org/?gist=ce6ea31715bee2b65f3da374fd39181c

Upvotes: 1

Related Questions