Skip to content

Instantly share code, notes, and snippets.

Embed
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))
@PierreBdR

This comment has been minimized.

Copy link

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.

@mrfabbri

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.