在递归方案中,我如何构造带有类型定义的内容,例如(Recursive t, CoRecursive t) -> t -> ? -> t
我尝试使用递归方案来更新节点。以列表为例,我可以想出两种方法:

update :: [a] -> Natural -> a -> [a]
update = para palg where
  palg Nil _ _ = []
  palg (Cons a (u, _)) 0 b = b : u
  palg (Cons a (u, f)) n b = a : f (n-1) b

update' :: [a] -> Natural -> a -> [a]
update' = c2 (apo acoalg) where
  c2 f a b c = f (a,b,c)
  acoalg ([], _, _) = Nil
  acoalg (_:as , 0, b) = Cons b $ Left as
  acoalg (a:as , n, b) = Cons a $ Right (as, n-1, b)

但是,这两个实现是好的。在这两种实现中,ListF[]的构造函数出现在等式的两侧。而且该定义似乎不是唯一的。有没有更好的方法来执行带有递归方案的列表更新?

最佳答案

递归方案是一种灵活的方法。您也可以实现自己的变体。

(重用cata)

zipo :: (Recursive g, Recursive h) => (Base g (h -> c) -> Base h h -> c) -> g -> h -> c
zipo alg = cata zalg
 where
  zalg x = alg x <<< project

update :: forall a. [a] -> Natural -> a -> [a]
update xs n a = zipo alg n xs
  where
    alg :: Maybe ([a] -> [a]) -> ListF a [a] -> [a]
    alg _ Nil = []
    alg Nothing (Cons y ys) = a:ys
    alg (Just n') (Cons y ys) = y:(n' ys)

你也可以实现一些并行版本
zipCata :: (Recursive g, Recursive h) => ((g -> h -> r) -> Base g g -> Base h h -> r) -> g -> h -> r
zipCata phi x y = phi (zipCata phi) (project x) (project y)

update' :: forall a. [a] -> Natural -> a -> [a]
update' xs n a = zipCata alg n xs
  where
    alg :: (Natural -> [a] -> [a]) -> Maybe Natural -> ListF a [a] -> [a]
    alg _ _ Nil = []
    alg _ Nothing (Cons _ ys) = a:ys
    alg f (Just n) (Cons y ys) = y:(f n ys)

两种变体(也与您一样)将获得相同的结果

PS。我讨厌SO上的代码示例的方法

09-05 22:14