Created
March 1, 2011 08:26
-
-
Save cushon/848817 to your computer and use it in GitHub Desktop.
Lazy generation of Hamming numbers in PLT Racket
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
(define (hamming) | |
(lcons 1 (lfoldr merge (map (lambda (p) (map (lambda (x) (* p x)) (hamming))) | |
(lazy-list 2 3 5))))) | |
; lazy-list library | |
(define-syntax lcons | |
(syntax-rules () | |
((_ a b) (lambda (f) (f a (lambda () b)))))) | |
(define (lazy-list . x) | |
(foldr (lambda (x y) (lcons x y)) '() x)) | |
(define (lcar l) (l (lambda (x y) x))) | |
(define (lcdr l) (l (lambda (x y) (y)))) | |
; lazy-map | |
(define (map f l) | |
(if (empty? l) '() (lcons (f (lcar l)) (map f (lcdr l))))) | |
; lazy-merge | |
(define (merge a b) | |
(cond [(< (lcar a) (lcar b)) (lcons (lcar a) (merge (lcdr a) b))] | |
[(= (lcar a) (lcar b)) (lcons (lcar a) (merge (lcdr a) (lcdr b)))] | |
[(> (lcar a) (lcar b)) (lcons (lcar b) (merge a (lcdr b)))])) | |
; foldr with lazy-list support | |
(define (lfoldr f l) | |
(if (empty? (lcdr l)) (lcar l) (f (lcar l) (lfoldr f (lcdr l))))) | |
(define (print n l) | |
(if (zero? n) (void) | |
(begin (printf "~a\n" (lcar l)) | |
(print (sub1 n) (lcdr l))))) | |
(print 62 (hamming)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment