<div dir="ltr">Hello all,<br><br>This is a really helpful list: I've learned half a dozen new things just by reading this month's traffic. Anyway...I have the following bit of code that updates a tree structure given a route to a leaf:<br>
<br>data Tree a = Leaf a | Node (Tree a) (Tree a)<br> deriving (Show, Eq)<br>data PathSelector = GoLeft | GoRight<br> deriving (Show, Eq)<br>type Path = [PathSelector] <br>
<br>selectChild (Node left _) GoLeft = left<br>selectChild (Node _ right ) GoRight = right<br><br>updateNode (Node _ right) GoLeft newLeft = Node newLeft right<br>updateNode (Node left _) GoRight newRight = Node left newRight<br>
<br>updateLeaf new (Leaf previous) = Leaf new<br><br>updateTree :: Tree a -> Path -> a -> Tree a<br>updateTree tree path newValue = case path of<br> [] -> updateLeaf newValue tree<br>
(p:ps) -> updateNode tree p (updateTree' (selectChild tree p) ps newValue)<br><br>I wanted to rewrite updateTree without using explicit recursion. Unfortunately, the best I could come up with is:<br>
<br>upDownRecurse :: (a -> b -> a) -> (a -> c) -> (a -> b -> c -> c) -> a -> [b] -> c<br>upDownRecurse down bottoming up = upDownRecurse'<br> where upDownRecurse' acc [] = bottoming acc<br>
upDownRecurse' acc (x:xs) = up acc x (upDownRecurse' (down acc x) xs)<br><br>updateTree' :: Tree a -> Path -> a -> Tree a<br>updateTree' tree path newValue = upDownRecurse selectChild (updateLeaf newValue) updateNode tree path<br>
<br>So what's the sexier way of doing this? <br><br>Cheers,<br><br>-- Matt<br></div>