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
;; cut, compose | |
(use srfi-1) | |
(define (make-fizzbuzz min max) | |
(map (lambda (n) | |
(let ((p (compose zero? (cut modulo n <>)))) | |
(cond ((p 15) "fizzbuzz") | |
((p 5) "buzz") | |
((p 3) "fizz") | |
(else n)))) | |
(iota max min))) | |
(define (fizzbuzz) | |
(make-fizzbuzz 1 100)) | |
(display (fizzbuzz)) |
関係ないけどfold-right。
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
;; fold-right | |
(display | |
(fold-right (lambda (e acc) | |
(let ((p (compose zero? (cut modulo e <>)))) | |
(cons (cond ((p 15) "fizzbuzz") | |
((p 5) "buzz") | |
((p 3) "fizz") | |
(else e)) acc))) | |
'() (iota 100 1))) |
確かsicpの2章にcomposeと一緒にrepeatedってのが出てたような。
ところでsicpって「シックピー(sick-pea)」と読むらしいですね。srfi同様「えすあいしーぴー」って読んでました。
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
;; repeated | |
(define (repeated n f) | |
(lambda (x) | |
(if (zero? n) | |
x | |
((repeated (- n 1) f)(f x))))) | |
((repeated 3 (lambda (x) | |
(* x 3))) 3) | |
; -> 81 | |
((repeated 3 (cut * <> 3)) 3) | |
; -> 81 | |
(define (repeated n f) | |
(lambda (x) | |
(letrec ((rep (lambda (n acc) | |
(if (zero? n) | |
(acc x) | |
(rep (- n 1) | |
(lambda (y) | |
(f (acc y)))))))) | |
(rep n identity)))) | |
((repeated 5 (cut * <> 2)) 2) | |
; -> 64 | |
(define (repeated n f) | |
(lambda (x) | |
(let loop ((n n) | |
(acc identity)) | |
(if (zero? n) | |
(acc x) | |
(loop (- n 1) | |
(lambda (y) | |
(f (acc y)))))))) | |
((repeated 5 (cut * <> 2)) 2) | |
; -> 64 |
一般的な再帰からnamed-letに書き直せない病。(letrecを経由するといける)
0 件のコメント:
コメントを投稿