2010/09/06

append

ちゃんと書こうとすると、意外と難しいですね。

これだと (append '() 1) が 1 にならないですね。
(define (append1 ls1 ls2)
(let rec ((ls (reverse ls1))(acc ls2))
(if (null? ls)
acc
(rec (cdr ls)(cons (car ls) acc)))))
(append1 '(1 2 3)'(4 5 6))
;; (1 2 3 4 5 6)
(use srfi-1)
(define (append1 ls1 ls2)
(fold-right cons ls2 ls1))
(define (append ls . lss)
(fold-right append1 '() (cons ls lss)))
(append1 '() 1)
;; 1
(append '(1 2 3)'(4 5 6)'(7 8 9))
;; (1 2 3 4 5 6 7 8 9)
(append '() 1)
;; error
(with-module gauche (append '() 1))
;; 1
view raw append-1.scm hosted with ❤ by GitHub

こんな感じでしょうか。
(define (append . lss)
(if (null? lss)
'()
(let rec ((lss lss))
(if (null? (cdr lss))
(car lss)
(fold-right cons (rec (cdr lss))(car lss))))))
(append '(1 2 3)'(4 5 6)'(7 8 9))
;; (1 2 3 4 5 6 7 8 9)
(append '() 1)
;; error
(with-module gauche (append))
;; ()
(append)
;; ()
view raw append-2.scm hosted with ❤ by GitHub


最近、諸事情により昼間にパソコンを開く時間があまりありません。。

追記

(use srfi-1)
(define (list-append x . n)
  (if (null? n)
      x
      (unfold null? car cdr x
              (lambda _
                (apply list-append n)))))

なるほど!そういえば・・・

追記2

reduce-right!
(use srfi-1)
(define (list-append . xss)
 (reduce-right append1 '() xss))

The Little Schemer, 4th Edition

0 件のコメント:

コメントを投稿