Land of Lisp
(オライリージャパン)
M.D. Conrad Barski (著) 川合 史朗 (翻訳)
原書: Land of LISP
Learn to Program in Lisp, One Game at a Time!
開発環境
- OS X El Capitan - Apple (OS)
- Emacs(Text Editor)
- Scheme (プログラミング言語)
- kscheme (github), Gauche, MIT/GNU Scheme, GNU Guile (処理系)
Land of Lisp (M.D. Conrad Barski (著)、川合 史朗 (翻訳)、オライリージャパン)の第2部(LISP は対称なり)、9章(より進んだデータ型とジェネリックプログラミング)、9.4(データをジェネリックに扱う、シーケンスを使う、さらに二つの重要なシーケンス関数)を Scheme で取り組んでみる。
9.4(データをジェネリックに扱う、シーケンスを使う、さらに二つの重要なシーケンス関数)
コード(Emacs)
(begin
(define print (lambda (obj) (write obj) (newline)))
(define (sequence? obj) (or (list? obj) (string? obj) (vector? obj)))
(define (sequence->list obj)
(if (not (sequence? obj))
(begin (write "Invalid type: sequence->list -- ")
(print obj))
(cond ((list? obj) obj)
((string? obj) (string->list obj))
((vector? obj) (vector->list obj)))))
(define (subsequence seq start end)
(define (sub-list items start end)
(define (iter result n)
(if (or (= n end) (null? items))
(reverse result)
(iter (cons (list-ref items n) result) (+ n 1))))
(iter '() start))
(define (sub-vector vect start end)
(list->vector (sub-list (vector->list vect) start end)))
(cond ((string? seq) (string-copy seq start end))
((list? seq) (sub-list seq start end))
((vector? seq) (sub-vector seq start end))
(else (write "Invalid type: subsequence -- ")
(print seq))))
(define (sort items cmp)
(if (null? items)
'()
(let ((pivot (car items))
(rest (cdr items))
(smaller '())
(bigger '()))
(define (iter items)
(cond ((null? items)
(append (sort smaller cmp)
(cons pivot
(sort bigger cmp))))
((cmp (car items) pivot)
(set! smaller (cons (car items) smaller))
(iter (cdr items)))
(else
(set! bigger (cons (car items) bigger))
(iter (cdr items)))))
(iter rest))))
(print (subsequence "america" 2 6))
(print (subsequence '(a b c d e f g) 2 6))
(print (subsequence #(a b c d e f g) 2 6))
(print (sort '(5 8 2 4 9 3 6) <))
(print (sort '(5 8 2 4 9 3 6) >))
(print (sort (list #\e #\a #\d #\b #\c) char<?))
(print (sort (list #\e #\a #\d #\b #\c) char>?))
(print (sort '() <))
(print (sort '(5 10 10 5) <))
)
入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))
$ ./kscheme sample4_3.scm "eric" (c d e f) #(c d e f) (2 3 4 5 6 8 9) (9 8 6 5 4 3 2) (#\a #\b #\c #\d #\e) (#\e #\d #\c #\b #\a) () (5 5 10 10) $
0 コメント:
コメントを投稿