The Little Schemer の8章で継続渡しが少し出てきます。
この章から本格的に継続渡し・呼び出しが出てくるようです。
call/cc, letcc(let/cc)など。
ここで書いてるintersectは継続とは無関係で、その前振りです。
intersectallなどを経て、letcc, call-witch-current-continuationを使って書いてみるよー!と進んでいきます。
一般的な再帰、letrec、fold-rightなどで書いてみました。
fold系は便利ですね。
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
; intersect | |
; (intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) | |
; normal recur | |
(define (intersect set1 set2) | |
(cond ((or (null? set1) | |
(null? set2)) '()) | |
((member? (car set1) set2) (cons (car set1) | |
(intersect (cdr set1) set2))) | |
(else (intersect (cdr set1) set2)))) | |
(intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) | |
; normal recur | |
(define (intersect set1 set2) | |
(if (or (null? set1) | |
(null? set2)) | |
'() | |
(let ((a (car set1)) | |
(n (intersect (cdr set1) set2))) | |
(if (member? a set2) | |
(cons a n) | |
n)))) | |
(intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) | |
; fold-right | |
(use srfi-1) | |
(define (intersect set1 set2) | |
(fold-right (lambda (e acc) | |
(if (member? e set2) | |
(cons e acc) | |
acc)) | |
'() | |
set1)) | |
(intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) | |
; letrec | |
(define (intersect set1 set2) | |
(letrec | |
((int (lambda (s acc) | |
(cond ((null? s) '()) | |
((member? (car s) set2) | |
(cons (car s)(int (cdr s) acc))) | |
(else (int (cdr s) acc)))))) | |
(if (or (null? set1) | |
(null? set2)) | |
'() | |
(int set1 '())))) | |
(intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) | |
; letrec | |
(define (intersect set1 set2) | |
(letrec | |
((int (lambda (s acc) | |
(if (null? s) | |
acc | |
(let ((a (car s)) | |
(n (int (cdr s) acc))) | |
(if (member? a set2) | |
(cons a n) | |
n)))))) | |
(if (or (null? set1) | |
(null? set2)) | |
'() | |
(int set1 '())))) | |
(intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) | |
; The Seasoned Schemer | |
(define intersect | |
(lambda (set1 set2) | |
(cond | |
((null? set1)(quote ())) | |
((member? (car set1) set2) | |
(cons (car set1) | |
(intersect (cdr set1) set2))) | |
(else (intersect (cdr set1) set2))))) | |
(intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) | |
; The Seasoned Schemer letrec | |
(define intersect | |
(lambda (set1 set2) | |
(letrec | |
((I (lambda (set) | |
(cond | |
((null? set)(quote ())) | |
((member? (car set) set2) | |
(cons (car set) | |
(I (cdr set)))) | |
(else (I (cdr set))))))) | |
(I set1)))) | |
(intersect '(tomatoes and macaroni) '(macaroni and cheese)) | |
; -> (and macaroni) |
0 件のコメント:
コメントを投稿