gpt4 book ai didi

haskell - 门德勒的组织形态论

转载 作者:行者123 更新时间:2023-12-02 12:10:51 25 4
gpt4 key购买 nike

使用 recursion-schemes 中的组织同态 (histo)我可以从初始列表中获取仅包含奇数索引的列表:

import Data.Functor.Foldable

odds :: [a] -> [a]
odds = histo $ \case
Nil -> []
Cons h (_ :< Nil) -> [h]
Cons h (_ :< Cons _ (t :< _)) -> h:t

如何使用 mhisto 获得相同的结果?

nil      = Fix Nil
cons a b = Fix $ Cons a b
list = cons 1 $ cons 2 $ cons 3 $ nil

modds :: Fix (ListF a) -> [a]
modds = mhisto alg where
alg _ _ Nil = []
alg f g (Cons a b) = ?

最佳答案

就是这样:

modds :: Fix (ListF a) -> [a]
modds = mhisto alg
where
alg _ _ Nil = []
alg odd pre (Cons a b) = a : case pre b of
Nil -> []
Cons _ b' -> odd b'
GHCi> list = cata embed [1..10] :: Fix (ListF Int)
GHCi> odds (cata embed list)
[1,3,5,7,9]
GHCi> modds list
[1,3,5,7,9]

odd 折叠列表的其余部分,而 pre 挖掘前一个。请注意门德勒代数中 y -> f y 函数的可用性如何反射(reflect)了普通组织同态代数中 Cofree 的引入(其中可以通过获取来进行回溯) Cofree 流的尾部):

cata  :: Functor f => (f c -> c) -> Fix f -> c
histo :: Functor f => (f (Cofree f c) -> c) -> Fix f -> c

mcata :: (forall y. (y -> c) -> f y -> c) -> Fix f -> c
mhisto :: (forall y. (y -> c) -> (y -> f y) -> f y -> c) -> Fix f -> c

有关 mcatamhisto 的进一步阅读,请参阅 Categorical programming with inductive and coinductive types, by Varmo Vene 的第 5 章和第 6 章.

关于haskell - 门德勒的组织形态论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53126614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com