A faster implementation of stream-constant
Chris Jester-Young 31 Oct 2015 00:47 UTC
The reference implementation of stream-constant is O(n²) on the number
of elements passed in. There's a portable way to improve on that; here's
an implementation (based on the reference implementation):
(define (stream-constant . objs)
(cond ((null? objs) stream-null)
((null? (cdr objs)) (stream-let loop () (stream-cons (car objs) (loop))))
(else (let ((strm (list->stream objs)))
(stream-let loop () (stream-append strm (loop)))))))
Running `(stream-ref (apply stream-constant (range 5000)) 5000)` takes
8 seconds using the original version, and 4 milliseconds using the new
version, both running on DrRacket 6.2.1 on my computer.
If it looks good, it'd be nice to see it incorporated into the reference
implementation too. Comments welcome.
Cheers,
Chris.