Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Interleaving streams in Racket
#lang racket
;; produce a new stream with the elements of the given streams interleaved
(define (streams-interleave . streams)
(letrec ([loop (lambda (streams)
(let ([next ((car streams))])
(cons (car next)
(thunk (loop (append (cdr streams) (list (cdr next))))))))])
(thunk (loop streams))))
;; using interleave on some streams
(define (ones) (cons 1 ones))
(define (twos) (cons 2 twos))
(define (threes) (cons 3 threes))
(define interleaved (streams-interleave ones twos threes))

This comment has been minimized.

Copy link

@PierreBdR PierreBdR commented Nov 3, 2014

The second letrec is unnecessary, a simple let would be enough.
And in fact, this doesn't work!
Try inserting the list of natural numbers and you'll get only 1s from it.


This comment has been minimized.

Copy link
Owner Author

@mrfabbri mrfabbri commented Nov 3, 2014

Thanks Pierre! Good catch, corrected ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment