fold-rightで書いてみましたが、大丈夫かな。なんか怪しいような気もする。もしかするとfoldでreverseな方が良いかな。いやfold-rightで大丈夫か。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; flatten | |
;; (flatten '(1 2 3 (4 5 6 (7)((8) 9))((() 10)))) | |
;; -> (1 2 3 4 5 6 7 8 9 10) | |
(define (flatten tree) | |
(fold-right (lambda (e acc) | |
(cond | |
((null? e) acc) | |
((pair? e) | |
(append (flatten e) acc)) | |
(else (cons e acc)))) | |
'() tree)) | |
(flatten '(1 2 3 (4 5 6 (7)((8) 9))((() 10)))) | |
; -> (1 2 3 4 5 6 7 8 9 10) | |
追記
LOLより。Common Lispのlabelsはschemeのletrecみたいなもの、と考えて良いんだろう、きっと。なんかCLの方が美しい気がする(labelsに限らず)。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun flatten (x) | |
(labels ((rec (x acc) | |
(cond ((null x) acc) | |
((atom x) (cons x acc)) | |
(t (rec | |
(car x) | |
(rec (cdr x) acc)))))) | |
(rec x nil))) | |
(flatten '(1 2 3 (4 5 6 (7)((8) 9))((() 10)))) |
0 件のコメント:
コメントを投稿