我想教自己球拍。我目前正在嘗試編寫一個函數來幫助理解嵌套列表。該函數採用嵌套列表和過程,並將過程應用於每個元素以生成新列表。舉個例子:球拍嵌套列表和應用功能
(map-tree even? '(1 2 3 4)) => '(#f #t #f #t)
這裏是我到目前爲止有:
(define (map-tree proc tree)
(map-tree-aux tree proc '()))
(define (map-tree-aux tree proc lst)
(if (null? tree)
lst
(if (list? tree)
(if (null? (cdr tree))
(if (number? (car tree))
(map-tree-aux (car tree) proc (append-end (proc (car tree)) lst))
(map-tree-aux (car tree) proc lst))
(if (number? (car tree))
(map-tree-aux (cdr tree) proc (append-end (proc (car tree)) (map-tree-aux (car tree) proc lst)))
(map-tree-aux (cdr tree) proc lst)))
lst)))
(define (append-end elem lst)
(append lst (list elem)))
雖然這工作與我提供的原來的例子,更復雜的例子出來錯誤:
(map-tree even? '(1 (2 (3 (4))))) should be '(#f (#t (#f (#t)))), but is currently (#f #t #f #t).
我知道這只是一個問題,在某個地方「列出」,但我有一個問題,找出如何做到這一點。
我首先想到的是如果樹空,(car tree)
不是一個數字,但我得到我想要的東西相反(嵌套在相反方向的結果列表)應用程序list
向lst
。我非常感謝你的幫助。
謝謝!
這是過期的,但謝謝!你可以肯定地告訴我在努力去理解球拍的基礎知識,但是我很欣賞你花時間去了解我的基本知識:)。 – mrdjl