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

1

13
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
Indreetloire answered 30/8, 2015 at 10:10 Comment(0)
F
14

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)
Floss answered 30/8, 2015 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.