如何使用递归方案更新结构?

How to update a structure with recursion schemes?

在递归方案中,我如何构造类型定义为 (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

上的代码示例方法