Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cushon
Created March 1, 2011 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cushon/848817 to your computer and use it in GitHub Desktop.
Save cushon/848817 to your computer and use it in GitHub Desktop.
Lazy generation of Hamming numbers in PLT Racket
(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