haskell - 使用 GADT 实现类型类

标签 haskell gadt

我在 Haskell 中编写了以下线性代数向量

data Natural where
    Zero :: Natural
    Succ :: Natural -> Natural

data Vector n e where
    Nil :: Vector Zero e
    (:|) :: (Show e, Num e) => e -> Vector n e -> Vector (Succ n) e
infixr :|

instance Foldable -- ... Vector ..., but how do I implement this?

当我尝试实现 Foldable 时,我遇到了 ZeroSucc 有不同定义的问题(即 * 和 * -> *).

这个问题有明显的解决方案吗?

最佳答案

只是

instance Foldable (Vector n) where
  fold Nil       = mempty
  fold (a :| as) = a <> fold as

不过,我不建议向 e 类型添加约束。

关于haskell - 使用 GADT 实现类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23919030/

相关文章:

haskell - "Type constructed with type argument"的实例不需要用该类型的数据构造,在 Haskell 中

Agda 中的 Haskell 部分

haskell - GADT : Difference between 'Algebraic' and 'Abstract' ?

haskell - 从评估级别访问 GADT 约束

haskell - 如何用 GADT 表示变量类型的构造函数列表?

syntax - OCaml 的 `type a. a t` 语法

haskell - 从 monad 翻译为 applicative

haskell - 等式推理的名称从何而来?

Haskell:if-then-else block 和具有非对称构造函数的数据

haskell - Haskell 中嵌套对是个好主意吗