foldでは書けないよなー、と思い探してみるとfold2なるものがgauche.collectionにありました。
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
; letting excersise scramble | |
(define (pick n lat) | |
(list-ref lat (- n 1))) | |
; The Seasoned Schemer | |
(define scramble | |
(lambda (tup) | |
(letrec | |
((P (lambda (tup rp) | |
(cond | |
((null? tup)(quote ())) | |
(else | |
(let ((rp (cons (car tup) rp))) | |
(cons (pick (car tup) rp) | |
(P (cdr tup) rp)))))))) | |
(P tup (quote ()))))) | |
(define (scramble tup) | |
(letrec | |
((P (lambda (tup rp) | |
(if (null? tup) | |
'() | |
(let ((rp (cons (car tup) rp))) | |
(cons (pick (car tup) rp) | |
(P (cdr tup) rp))))))) | |
(P tup '()))) | |
; again | |
(define (scramble tup) | |
(letrec | |
((P (lambda (tup rp) | |
(if (null? tup) | |
'() | |
(let ((kar (car tup))) | |
(let ((rp (cons kar rp))) | |
(cons (pick kar rp) | |
(P (cdr tup) rp)))))))) | |
(P tup '()))) |
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
; named let | |
(define (scramble tup) | |
(let loop ((tup tup) | |
(rp '())) | |
(if (null? tup) | |
'() | |
(let ((kar (car tup))) | |
(let ((rp (cons kar rp))) | |
(cons (pick kar rp) | |
(loop (cdr tup) rp))))))) |
reverse格好悪い・・・。
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
; fold2 | |
(use gauche.collection) | |
(define (scramble tup) | |
(reverse | |
(fold2 (lambda (e acc rp) | |
(let ((rp (cons e rp))) | |
(values (cons (list-ref rp (- e 1)) | |
acc) | |
rp))) | |
'() '() tup))) | |
(scramble '(1 2 3 4 5 6 7 8 9)) |
0 件のコメント:
コメントを投稿