ais*_*ais 13 haskell functor comonad foldable
data Tree t = Empty | Node t (Tree t) (Tree t)
Run Code Online (Sandbox Code Playgroud)
我们可以创建Functor实例并使用
fmap :: (t -> a) -> Tree t -> Tree a
Run Code Online (Sandbox Code Playgroud)
但是如果不是(t - > a)我想要(树t - > a)那么我可以访问整个(节点t)而不仅仅是t
treeMap :: (Tree t -> a) -> Tree t -> Tree a
treeMap f Empty = Empty
treeMap f n@(Node _ l r) = Node (f n) (treeMap f l) (treeMap f r)
Run Code Online (Sandbox Code Playgroud)
与折叠相同
treeFold :: (Tree t -> a -> a) -> a -> Tree t -> a
Run Code Online (Sandbox Code Playgroud)
对这些功能有任何概括吗?
map :: (f t -> a) -> f t -> f a
fold :: (f t -> a -> a) -> a -> f t -> a
Run Code Online (Sandbox Code Playgroud)
lef*_*out 14
你刚刚发现了comonads!好吧,差不多.
class Functor f => Comonad f where
extract :: f a -> a
duplicate :: f a -> f (f a)
instance Comonad Tree where
extract (Node x _ _) = x -- this one only works if your trees are guaranteed non-empty
duplicate t@(Node n b1 b2) = Node t (duplicate b1) (duplicate b2)
Run Code Online (Sandbox Code Playgroud)
随着duplicate你可以实现你的功能:
treeMap f = fmap f . duplicate
freeFold f i = foldr f i . duplicate
Run Code Online (Sandbox Code Playgroud)
要正确执行此操作,您应该通过类型系统强制执行非空白:
type Tree' a = Maybe (Tree'' a)
data Tree'' t = Node' t (Tree' t) (Tree' t)
deriving (Functor)
instance Comonad Tree'' where
extract (Node' x _ _) = x
duplicate t@(Node' _ b1 b2) = Node' t (fmap duplicate b1) (fmap duplicate b2)
Run Code Online (Sandbox Code Playgroud)