Last active
December 18, 2015 23:09
-
-
Save zachallaun/5860012 to your computer and use it in GitHub Desktop.
Toy lazy sequences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// LazySeq(head, tailthunk) -> more to go | |
// LazySeq(head, new Empty) -> end of sequence | |
function LazySeq(head, tailthunk) { | |
this.head = head | |
this.tail = tailthunk | |
} | |
function Empty() {} | |
var empty = new Empty | |
// function ints(from) { | |
// return new LazySeq(from, function() { return ints(from + 1) }) | |
// } | |
LazySeq.prototype.map = function(fn) { | |
var self = this | |
return new LazySeq(fn(this.head), function() { | |
return this.tail().map(fn) | |
}.bind(this)) | |
} | |
Empty.prototype.map = function() { return this } | |
// ints(0).map(function(x) { return x + 1 }) ~= ints(1) | |
LazySeq.prototype.filter = function(pred) { | |
if (pred(this.head)) { | |
return new LazySeq(this.head, function() { | |
return this.tail().filter(pred) | |
}.bind(this)) | |
} else { | |
return this.tail().filter(pred) | |
} | |
} | |
Empty.prototype.filter = function() { return this } | |
// var evens = ints(0).filter(function(x) { return x%2===0 }) | |
LazySeq.prototype.take = function(n) { | |
if (n === 0) { | |
return empty | |
} else { | |
return new LazySeq(this.head, function() { | |
return this.tail().take(n - 1) | |
}.bind(this)) | |
} | |
} | |
Empty.prototype.take = function() { return this } | |
// ints(0).take(10) ~= 0 through 9 | |
LazySeq.prototype.forEach = function(fn) { | |
fn(this.head) | |
this.tail().forEach(fn) | |
} | |
Empty.prototype.forEach = function(){} | |
LazySeq.prototype.reduce = function(init, fn) { | |
var acc = init | |
this.forEach(function(el) { | |
acc = fn(acc, el) | |
}) | |
return acc | |
} | |
Empty.prototype.reduce = function(init) { return init } | |
// ints(1).take(5).reduce(0, function(x, y) { return x + y }) === 15 | |
LazySeq.prototype.toArray = function () { | |
return this.reduce([], function(arr, el) { | |
arr.push(el) | |
return arr | |
}) | |
} | |
Empty.prototype.toArray = function() { return [] } | |
// ints(1).take(5).toArray() ~= [0, 1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment