Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Last active December 18, 2015 23:09
Show Gist options
  • Save zachallaun/5860012 to your computer and use it in GitHub Desktop.
Save zachallaun/5860012 to your computer and use it in GitHub Desktop.
Toy lazy sequences
// 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