2

我在 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

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

4

2 回答 2

5

只是

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

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

于 2014-05-28T18:29:15.270 回答
3

您无需在类实例中提及Zero或提及Succ,这就是 GADT 的全部要点:构造函数上的模式匹配为您提供类型信息:

instance F.Foldable (Vector v) where
  foldr _ zero Nil = zero
  foldr f zero (e0 :| v) = f e0 $ F.foldr f zero v 
于 2014-05-28T18:28:02.377 回答