13
data Tree t = Empty | Node t (Tree t) (Tree t)

我们可以创建 Functor 实例并使用

fmap :: (t -> a) -> Tree t -> Tree a

但是,如果我想要 (Tree t -> a) 而不是 (t -> a) 那么我可以访问整个 (Node 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)

与折叠相同

treeFold :: (Tree t -> a -> a) -> a -> Tree t -> a

对这些函数有什么概括吗?

map :: (f t -> a) -> f t -> f a
fold ::  (f t -> a -> a) -> a -> f t -> a
4

1 回答 1

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)

duplicate你可以实现你的功能:

treeMap f = fmap f . duplicate
freeFold f i = foldr f i . duplicate

要正确执行此操作,您应该通过类型系统强制执行非空:

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)
于 2015-08-30T10:21:45.130 回答