编写RoseTree元素计数函数遇异常:结果应为27却返回4求助
Fixing Your
roseSize Function for Rose Trees Hey there, let's work through why your roseSize function is returning 4 instead of the correct total of 27. First, let's break down where your current code is going wrong:
What's Off With the Original Implementation
Your current code has two critical mistakes that throw off the count:
roseSize x = case x of RoseNode a [] -> 0 RoseNode a (x:xs) -> 1 + roseSize (RoseNode a xs)
- Leaf nodes are being ignored: The first pattern matches a node with no children, but this node itself is still one element! Returning
0here undercounts every single leaf in your tree. - You're not traversing nested child trees: The second pattern takes the first child
xbut never calculates its size—instead, you're just passing the remaining children listxsback as a new node's children. This means you're only counting the number of direct child groups, not all the nested nodes inside each child tree. That's why you get 4: it's just the root node plus the 3 remaining child groups in the root's list.
The Correct Approach
To get the total number of elements in a RoseTree, you need to:
- Count the current node (add 1 to the total)
- Recursively calculate the size of every child tree and sum all those sizes
Here's the fixed function that follows this logic:
roseSize :: RoseTree a -> Int roseSize (RoseNode _ children) = 1 + sum (map roseSize children)
If you prefer to stick with case syntax (matching your original style), this equivalent version works too:
roseSize x = case x of RoseNode a children -> 1 + sum (map roseSize children)
Why This Works for Your things Tree
Let's verify the count step-by-step:
- The root node contributes 1
- For each child of the root, we calculate its full subtree size and add them up:
- "animal" subtree: 1 (animal) + 2 (cat, dog) = 3
- "metal" subtree: 1 (metal) + 3 (alloy + steel + bronze) + 4 (element + gold + tin + iron) = 8
- "fruit" subtree: 1 (fruit) + 3 (apple + Granny Smith + Pink Lady) + 1 (banana) + 1 (orange) = 6
- "astronomical object" subtree: 1 + 3 (Planet + Earth + Mars) + 3 (Star + Sun + Sirius) + 2 (Galaxy + Milky Way) = 9
- Adding it all together: 1 + 3 + 8 + 6 + 9 = 27, which matches the correct total.
内容的提问来源于stack exchange,提问作者Kafai Law
相关产品推荐
相关产品推荐

