根据Bartosz Milewski的文章(一,二),我定义了一个F代数:
(这并不是说我的代码是Bartosz思想的一个确切体现,它仅仅是我对它们的有限理解,而且任何缺陷都是我自己的.)
module Algebra where
data Expr a = Branch [a] | Leaf Int
instance Functor Expr where
fmap f (Branch xs) = Branch (fmap f xs)
fmap _ (Leaf i ) = Leaf i
newtype Fix a = Fix { unFix :: a (Fix a) }
branch = Fix . Branch
leaf = Fix . Leaf
-- | This is an example algebra.
evalSum (Branch xs) = sum xs
evalSum (Leaf i …Run Code Online (Sandbox Code Playgroud) 据我所知,我们可以通过Coyoneda免费获得仿函数.但是存在一些haskell包http://hackage.haskell.org/package/free-functors
我的问题是,Coyoneda和http://hackage.haskell.org/package/free-functors-0.8.1/docs/src/Data-Functor-Free.html#Free之间有什么区别
我有一个AST,我正在使用它进行注释Cofree:
data ExprF a
= Const Int
| Add a
a
| Mul a
a
deriving (Show, Eq, Functor)
Run Code Online (Sandbox Code Playgroud)
我type Expr = Fix ExprF用来表示未标记的AST,并type AnnExpr a = Cofree ExprF a代表标记的AST .我已经找到了一个函数,通过丢弃所有注释将标记的AST转换为未标记的AST:
forget :: Functor f => Cofree f a -> Fix f
forget = Fix . fmap uncofree . unwrap
Run Code Online (Sandbox Code Playgroud)
这看起来可能是某种类似的catamorphism(我正在使用Kmett的recursion-schemes包中的定义).
cata :: (Base t a -> a) -> t -> a
cata f = c where c = f . fmap …Run Code Online (Sandbox Code Playgroud) haskell functional-programming category-theory catamorphism recursion-schemes