实现inverse-tree过程:反转树节点数值与布尔值
Implementing the
inverse-tree Procedure in Scheme Alright, let's break down how to build this inverse-tree function for Scheme. The task is straightforward: take a tree where each node is either a number or boolean, and return a mirror tree where numbers are negated (multiplied by -1) and booleans are flipped (logical NOT). Empty trees stay empty, and we need to handle all nested subtrees recursively.
Step 1: Define the Core Logic
Here's the implementation that covers all cases:
(define (inverse-tree tree) (cond ; Base case: empty tree returns empty ((null? tree) '()) ; Handle leaf nodes (non-list values) ((not (pair? tree)) (cond ((number? tree) (- tree)) ; Negate numbers ((boolean? tree) (not tree)) ; Flip booleans ; Optional: pass through unexpected types (per problem statement, this shouldn't happen) (else tree))) ; Recursive case: process every subtree in the list (else (map inverse-tree tree))))
Step 2: Test the Examples
Let's verify with the test cases you mentioned:
(inverse-tree ’()) → ’()
(inverse-tree ’(5)) → ’(-5)
And a few more to ensure nested trees work correctly:
(inverse-tree #t)→#f(inverse-tree '(#f 3 (2 #t)))→'(#t -3 (-2 #f))
How It Works
- Empty Tree Check: First, we handle the base case where the input is an empty list—we just return the empty list right away.
- Leaf Nodes: If the input isn't a list (meaning it's a single number or boolean), we check its type:
- For numbers, we use
-to negate the value (since- xis equivalent tox * -1in Scheme). - For booleans, we use the built-in
notfunction to flip the value.
- For numbers, we use
- Nested Trees: If the input is a list (a tree with subtrees), we use
mapto applyinverse-treeto every element in the list. This recursively processes every subtree, no matter how deep they are.
内容的提问来源于stack exchange,提问作者Adam Morad
相关产品推荐
相关产品推荐

