2010/09/22

Re: schemeで全dataを+するのを知りたいです、か?

私もやってみました。

mysum
;; http://d.hatena.ne.jp/yad-EL/20100921/p1
;; (mysum 20) => error
;; (mysum '()) => 0
;; (mysum '(1 2 3)) => 6
;; (mysum '((1 2) ((3)) (4 (5)))) => 15
(define (tree-fold proc seed tree)
(if (list? tree)
(fold (lambda (e acc)
(if (list? e)
(tree-fold proc acc e)
(proc e acc))) seed tree)
(error "argument must be a list, but got")))
(define (mysum tree)
(tree-fold + 0 tree))
(mysum 20)
;; *** ERROR: argument must be a list, but got
(mysum '())
;; 0
(mysum '(1 2 3))
;; 6
(mysum '((1 2) ((3)) (4 (5))))
;; 15
view raw mysum.scm hosted with ❤ by GitHub

mytrans
;; http://d.hatena.ne.jp/yad-EL/20100921/p1
;; (mytrans 1) => error
;; (mytrans '()) => 0
;; (mytrans '(1 2 3)) => (one two three)
;; (mytrans '((1 2) ((3)) (4 (5 6)))) => ((one two) ((three)) (four (five six)))
(define (tree-map proc tree)
(map (lambda (e)
(if (list? e)
(tree-map proc e)
(proc e))) tree))
(define *table* '(zero one two three
four five six seven
eight nine ten))
(define (mytrans tree)
(cond ((not (list? tree))(error "argument must be a list, but got"))
((null? tree) 0)
(else (tree-map (lambda (e)
(list-ref *table* e)) tree))))
(mytrans 1)
;; *** ERROR: argument must be a list, but got
(mytrans '())
;; 0
(mytrans '(1 2 3))
;; (one two three)
(mytrans '((1 2) ((3)) (4 (5 6))))
;; ((one two) ((three)) (four (five six)))
view raw mytrans.scm hosted with ❤ by GitHub

myfind
;; http://d.hatena.ne.jp/yad-EL/20100921/p1
;; (myfind 10) => error
;; (myfind 'a) => error
;; (myfind '((x 10) (y 20) (x 30)) 'x) => 10
;; (myfind '((x 10) (y 20) (z 30)) 'i) => #f
(define (myfind ls key)
(let/cc hop
(fold (lambda (e seed)
(if (eq? key (car e))
(hop (cadr e))
seed))
#f ls)))
(myfind 10)
;; error
(myfind 'a)
;; error
(myfind '((x 10) (y 20) (x 30)) 'x)
(myfind '((x 10) (y 20) (z 30)) 'i) => #f
view raw myfind.scm hosted with ❤ by GitHub


プログラミングGauche

0 件のコメント:

コメントを投稿