Skip to content

Instantly share code, notes, and snippets.

@mrfabbri
Last active August 29, 2015 14:08
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 mrfabbri/7b3dbc506c7ba47cbea7 to your computer and use it in GitHub Desktop.
Save mrfabbri/7b3dbc506c7ba47cbea7 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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