Dao De Code

Helper functions for building streams in Racket

In Racket you can define streams which are kind of lazy lists.
So here are a couple of helper functions for easier stream creation:

; returns stream
(define (stream-builder seed current-element next-element)
  (letrec ([lazy-seq (lambda (x)
                       (cons (current-element x) (lambda () (lazy-seq (next-element x)))))])
    (lambda () (lazy-seq seed))))

; returns stream built sequentially
(define (seq-stream-builder seed current-element)
  (stream-builder seed current-element (lambda (x) (+ 1 x))))

And usage:

(define nats (seq-stream-builder 1 identity)) ; define stream of natural numbers
(nats) ; returns '(1 . #<procedure>)
((cdr (nats))) ; returns '(2 . #<procedure>)
comments powered by Disqus