[英]Tree Functor and Foldable but with Nodes. Is there any generalization over it?
data Tree t = Empty | Node t (Tree t) (Tree t)
我們可以創建Functor實例並使用
fmap :: (t -> a) -> Tree t -> Tree a
但是如果不是(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)
與折疊相同
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
你剛剛發現了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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.