You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现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 - x is equivalent to x * -1 in Scheme).
    • For booleans, we use the built-in not function to flip the value.
  • Nested Trees: If the input is a list (a tree with subtrees), we use map to apply inverse-tree to every element in the list. This recursively processes every subtree, no matter how deep they are.

内容的提问来源于stack exchange,提问作者Adam Morad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:22:08