Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tree Functor and Foldable but with Nodes. Is there any generalization over it?

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

We can create Functor instance and use

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

But what if instead of (t -> a) I want (Tree t -> a) so I could have access to a whole (Node t) not just 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)

Same with fold

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

Is there any generalization over functions like these?

map :: (f t -> a) -> f t -> f a
fold ::  (f t -> a -> a) -> a -> f t -> a
like image 239
ais Avatar asked Aug 30 '15 10:08

ais


1 Answers

You've just discovered comonads! Well, almost.

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)

With duplicate you can implement your functions:

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

To do it properly, you should enforce non-emptyness by the type system:

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)
like image 157
leftaroundabout Avatar answered Oct 15 '22 07:10

leftaroundabout