Haskell树折叠问题:如何用fold重写foldRT函数?
Rewriting
foldRT using fold Got it, let's work through this. First, let's clarify what foldRT does: it traverses the tree in a right-node-left order, accumulating values by first processing the right subtree, combining that result with the current node's value via f, then using that new accumulator to process the left subtree.
To reimplement this with the generic fold, we can use fold to build up a composition of functions instead of directly computing a value. Here's the solution:
foldRT :: (a -> b -> b) -> b -> Tree a -> b foldRT f acc t = fold (\v rightFn leftFn -> leftFn . f v . rightFn) id t acc
How this works:
Let's unpack the logic step by step:
- For a
Leaf, thefoldreturns theidfunction (our base case forfoldisid). This makes sense because an empty tree leaves the accumulator unchanged. - For a
Branch v l r:rightFnis the function generated by folding the right subtreer—when applied to an accumulator, it gives exactly the result offoldRT f acc r.- We compose
f vwithrightFn:f v . rightFntakes an accumulator, processes the right subtree first, then appliesf vto that result (this matches thef v (foldRT f acc r)step in the originalfoldRT). - Finally, we compose the left subtree's function
leftFnwith that result:leftFn . (f v . rightFn)takes the intermediate value from the right-node step and uses it as the accumulator for processing the left subtree—exactly what the originalfoldRTdoes when recursing onl.
- Applying this final composed function to our initial
accgives the same result as the originalfoldRT.
Quick test example:
Take the tree Branch 1 (Branch 2 Leaf Leaf) (Branch 3 Leaf Leaf) and let f = (\x acc -> x : acc) (to build a list).
- The original
foldRT f []returns[2,1,3](right subtree first: 3, then current node 1, then left subtree 2). - Our rewritten version generates a function that does
2 : (1 : (3 : [])), which also gives[2,1,3]—perfect match.
内容的提问来源于stack exchange,提问作者matt
相关产品推荐
相关产品推荐

