3

我想实现可折叠的

data Constant a b = Constant a

这是我的直接尝试:

instance Foldable (Constant a) where
  foldr f b (Constant a) = f a b

我想了解的编译错误部分是:

Couldn't match expected type ‘a1’ with actual type ‘a’
‘a1’ is a rigid type variable bound by the type signature for
foldr :: (a1 -> b -> b) -> b -> Constant a a1 -> b

如您所见,折叠功能a1从我无法访问的常量中获取“幻像类型”(?);我只能访问a.

我该如何解决这个问题?请解释你的解决方案,因为我很困惑。

整个编译错误是:

try2/chap20/ex1.hs:9:30: Couldn't match expected type ‘a1’ with actual type ‘a’ …
      ‘a’ is a rigid type variable bound by
          the instance declaration
          at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:8:10
      ‘a1’ is a rigid type variable bound by
           the type signature for
             foldr :: (a1 -> b -> b) -> b -> Constant a a1 -> b
           at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:3
    Relevant bindings include
      a :: a
        (bound at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:23)
      f :: a1 -> b -> b
        (bound at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:9)
      foldr :: (a1 -> b -> b) -> b -> Constant a a1 -> b
        (bound at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:3)
    In the first argument of ‘f’, namely ‘a’
    In the expression: f a b
Compilation failed.
4

2 回答 2

9

Constant a b不包含任何b-s,所以我们将它折叠起来,就好像它是一个空的b-s 列表:

instance Foldable (Constant a) where
    foldr f z (Constant a) = z

ainConstant a b与实例无关Foldable,因为这只涉及最后一个参数。因此,您不能真正a在定义中使用。

于 2016-05-24T17:46:57.040 回答
2

我认为唯一的可能是:

data Constant a b = C a

-- foldMap :: Monoid m => (b -> m) -> t b -> m
instance Foldable (Constant a) where
  foldMap f (C a) = mempty

这是微不足道的解决方案。

看看为什么你可以为这个定义做这件事可能很有启发性:

data Constant' a b = C' b

-- foldMap :: Monoid m => (b -> m) -> t b -> m
instance Foldable (Constant' a) where
  foldMap f (C' a) = f a

tConstant' a,所以

  • 类型t bConstant' a b。这种类型的值具有C bval某些bval类型值的结构b
  • f有类型b -> m,所以我们可以f申请bval

但是,在另一种情况下,我们没有 fromb用于 apply to的值f,所以我们能做的最好的就是 return mempty

于 2016-05-24T17:45:13.020 回答