haskell - 如何为 Constant a b = Constant a 实现可折叠实例?

标签 haskell types foldable

我想为

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.

最佳答案

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

instance Foldable (Constant a) where
    foldr f z (Constant a) = z
aConstant a bFoldable 无关例如,因为那只涉及最后一个参数。因此你不能真正利用 a在你的定义中。

关于haskell - 如何为 Constant a b = Constant a 实现可折叠实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37419925/

相关文章:

haskell - 高阶多态性是否需要严格的参数顺序?

haskell - 如何理解 Haskell 的 "1.2 % 3.4"错误消息?

Python 类返回类型

php - 数组 - Orderby - 类型

haskell - 为什么在 Haskell 中最大值 (8,1) = 1?

list - 如何在 Haskell 中折叠状态?

haskell - 将元组转换为可折叠

list - 如何从列表中获取得分最高的项目

haskell - SYB : can a map over the result of listify be rewritten with a gfoldl?

java - 这行Java代码在做什么?