如何在foldMap中使用foldrDefault和foldlDefault?

时间:2017-09-15 02:02:22

标签: purescript

我正在尝试完成Phil Freeman的PureScript书第6.7节中的练习5。练习要求我为以下类型编写Foldable实例。

data NonEmpty a = NonEmpty a (Array a)

我通过实施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

但是会产生以下错误。

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

我认为我收到了错误,因为foldr = foldrDefault意味着编译器NonEmpty已经可折叠了,而这正是我想要实例的,但后来我不知道如何使用默认折叠实现。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为使用默认设置实际上不是问题。您似乎在您的实例上添加了一个我认为不需要的Foldable a约束。所以你的实例可以是:

instance foldableNonEmpty :: Foldable NonEmpty where

删除后,我认为其余的都是正确的!

我在try.purescript.org编辑器中进行了测试:http://try.purescript.org/?gist=ce6ea31715bee2b65f3da374fd39181c