如果它们为null,则Scheme会删除左右子项

时间:2015-07-03 09:55:57

标签: scheme

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

;; make-tree的定义;;

(define (make-tree entry left right)
  (list entry left right))

;;输入树;;

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

如果我这样做(打印树),则假设将输入树更改为

;;预期输出;;

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

;;

(define (print tree)
  (cond ((and (null? (cadr tree)) (null? (caddr tree)))
         (cons (car tree) '())
         (make-tree (car tree) (cadr tree) (caddr tree))
         (print tree)
         )))

但是在尝试(打印树)后我得到了换行符。有人可以帮助我获得预期的输出吗?

回复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
> 

1 个答案:

答案 0 :(得分:1)

此解决方案使用来自Racket的SELECT MCHI.UNIQUE_CONTAINER_ID, MCHI.CLIENT_BOX_BARCODE, MCHI.WMS_BOX_BARCODE, MCHI.BOX_SIZE, MCHI.STORAGE_LOCATION, dbo.TB_CHEVRON_CORE.WELL_NAME_LEASE, dbo.TB_CHEVRON_CORE.WELL, dbo.TB_CHEVRON_CORE.PROSPECT, dbo.TB_CHEVRON_CORE.UNIQUE_PROVINCE_ID, dbo.TB_CHEVRON_CORE.COUNTY_PARISH_BOROUGH, DPC.UNIQUE_PROVINCE_ID, DPC.STATE_PROVINCE FROM dbo.TB_MASTER_CONTAINER_HEADER_INFORMATION as MCHI, dbo.TB_CHEVRON_CORE, dict.DICT_PROVINCE_COUNTY INNER JOIN dbo.TB_CHEVRON_CORE AS CC ON MCHI.UNIQUE_CONTAINER_ID = CC.UNIQUE_CONTAINER_ID INNER JOIN dict.DICT_PROVINCE_COUNTY as DPC ON DPC.UNIQUE_PROVINCE_ID = CC.UNIQUE_PROVINCE_ID

match

树有四种不同的形状。

每个子句处理不同的形状。

如果您无法使用(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,则有四种情况。

更新

cond

变为

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