Hi all I've been messing about with streams in JavaScript, trying to implement some of the code from section 3.5 (http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#%_sec_3.5) of SICP.
Here's a fiddle showing the Sieve of Eratosthenes, displaying each prime as it is found. http://jsfiddle.net/skilldrick/vT2mC/1/ For the uninitiated, a stream is like a list where only the first element is calculated. The rest of the list is held as a "promise" to compute it later. The way I've implemented streams in JS is as an array, where the first element is the value, and the second element is a function that when called will return an array where the first element is the next value, and so on. There are two problems with implementing streams in JavaScript. The first is that there's no way (as far as I know) to abstract away the syntax in making a stream - so a function to make a stream looks like this: function integersFrom(start) { return [start, function () { return integersFrom(start + 1); }]; } whereas in Scheme it would be simply (define (integersFrom start) (cons-stream start (integersFrom (+ start 1)))) The second issue is that JS doesn't have tail-call optimisation, so working with long streams overflows the stack. If you look at the foreachStream function you'll see I'm doing a setTimeout each time I get a new value from the stream, but that then means the only way to return values is to go async. Anyway, just thought I'd share this, as I thought it might be interesting to others! -- Nick Morgan http://skilldrick.co.uk @skilldrick -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
