Scheme 如果左侧和右侧子项为空,则删除它们

Scheme 如果左侧和右侧子项为空,则删除它们,scheme,Scheme,我正在尝试编写方案代码(DrRaket或MIT),如果左、右子项为空,则删除它们 ;;生成树的定义 (define (make-tree entry left right) (list entry left right)) ;;输入树 (define tree (8 (5 (2 () ()) (4 () ())) (3 () (10 () ())))) 如果我这样做(打印树),假设将输入树更改为 ;;预期产出 (8 (5 (2)(4)) (3 () (10)))  但我在尝试(

我正在尝试编写方案代码(DrRaket或MIT),如果左、右子项为空,则删除它们

;;生成树的定义

(define (make-tree entry left right)
  (list entry left right))
;;输入树

(define tree (8 (5 (2 () ()) (4 () ())) (3 () (10 () ()))))
如果我这样做(打印树),假设将输入树更改为

;;预期产出

(8 (5 (2)(4)) (3 () (10)))

但我在尝试(打印树)后得到了换行符。有人能帮我得到预期的产量吗

回复soegaard 33的解决方案

(define (prune tree)
  (cond tree
    ((list x '()  '())    (list x))
    ((list x left '())    (list (prune left) (list x)))
    ((list x '()  right)  (list              (list x) (prune right)))
    ((list x left right)  (make-tree x (prune left) (prune right)))))

Output
Welcome to DrRacket, version 6.1.1 [3m].
Language: R5RS; memory limit: 128 MB.
. tree: bad syntax in: tree
> 

此解决方案使用来自Racket的
匹配

(define (prune tree)
  (match tree
    [(list x '()  '())    (list x)]
    [(list x left '())    (list (prune left) (list x))]
    [(list x '()  right)  (list              (list x) (prune right))]
    [(list x left right)  (make-tree x (prune left) (prune right))]))
这棵树有四种不同的形状

每个子句处理不同的形状

如果无法使用
匹配
将其更改为带有四个案例的
条件

更新:

(match tree
  ((list x '()  '())    (list x))
  ...
  ...)
变成

(cond 
  ((and (list? tree) 
        (null? (cadr tree))     ; the second element is '()
        (null? (caddr tree)))   ; the third  element is '()
   (list x))
  ...
  ...)

你需要建造一棵没有空叶子的树,还是只需要打印出来?@Soegard:我只需要打印出来。它不应该以任何方式改变树的结构。我必须使用make tree-through。@soegaard在他的解决方案中使用了
match
而不是
cond
。他们不一样!还要知道,
match
只在
#中起作用!球拍
除非您将
#的模式更改为
mlist
!r6rs
。您的
(定义树(8…)
可能无法工作-
8
不是一个函数。感谢您的解决方案。我从DrRacket收到以下消息:“欢迎使用DrRacket,版本6.1.1[3m]。语言:R5RS;内存限制:128 MB。阅读:非法使用开放方括号”是。这是一个
#lang racket
解决方案。您可以在R5RS中使用
cond
而不是
match
,但是您需要重写子句的左侧。还可以将所有[]更改为()。请查看您的解决方案的更新版本我已经厌倦了。我犯了语法错误。您是否发现有问题?如果使用
cond
您需要重写左侧。请参阅更新的答案。
(cond 
  ((and (list? tree) 
        (null? (cadr tree))     ; the second element is '()
        (null? (caddr tree)))   ; the third  element is '()
   (list x))
  ...
  ...)