I want to tag each element of a tree with a different value (Int, for example sake). I managed to do this but the code is ugly as a beast and I don’t know how to work with Monads yet.
My take:
data Tree a = Tree (a, [Tree a])
tag (Tree (x, l)) n = ((m, x), l')
where (m,l') = foldl g (n,[]) l
where g (n,r) x = let ff = tag x n in ((fst $ fst ff) +1, (Tree ff):r)
Do you know some better way?
EDIT:
I just realized that the above foldl really is mapAccumL. So, here is a cleaned version of the above:
import Data.List (mapAccumL)
data Tree a = Tree (a, [Tree a])
tag (Tree (x, l)) n = ((m,x),l')
where (m,l') = mapAccumL g n l
g n x = let ff@((f,_),_) = tag x n in (f+1,ff)
I’ve modified your types slightly. Study this code carefully:
EDIT: Same solution as above, but put through one round of refactoring into reusable pieces:
You can make
mapTreeMprocess the local value before the subtrees if you want:And using
Control.Monadyou can turn this into a one-liner: