Skip to content

Instantly share code, notes, and snippets.

@aboekhoff
Created February 7, 2010 17:14
Show Gist options
  • Save aboekhoff/297533 to your computer and use it in GitHub Desktop.
Save aboekhoff/297533 to your computer and use it in GitHub Desktop.
lang.EmptyCons = {
first: function() {return null;},
rest: function() {return lang.EmptyCons;},
seq: function() {return null;},
toString: function() {return "()";}
}
lang.Cons = function(_first, _rest) {
if (!_rest) { _rest = lang.EmptyCons; }
this._first = _first;
this._rest = _rest;
}
lang.Cons.prototype = {
first: function() {return this._first;},
rest: function() {return this._rest;},
seq: function() {return this;},
toString: function() {return lang.printSeq(this);}
}
lang.ArraySeq = function(array, index) {
if (index >= array.length) {
return lang.EmptyCons
}
this._array = array;
this._index = index;
}
lang.ArraySeq.prototype = {
first: function() {return this._array[this._index]},
rest: function() {return new lang.ArraySeq(this._array, this._index + 1)},
seq: function() {return this},
toString: function() {return lang.printSeq(this)}
}
lang.StringSeq = function(string, index) {
if (index >= string.length) {
return lang.EmptyCons;
}
this._string = string;
this._index = index;
}
lang.StringSeq.prototype = {
first: function() {return this._string.charAt(this._index)},
rest: function() {return new lang.StringSeq(this._string, this._index + 1)},
seq: function() {return this},
toString: function() {return lang.printSeq(this)}
}
Array.prototype.seq = function() {
return new lang.ArraySeq(this, 0)
}
String.prototype.seq = function() {
return new lang.StringSeq(this, 0);
}
lang.cons = function(x, coll) {
return new lang.Cons(x, coll.seq());
}
lang.first = function(coll) {
return coll.seq().first();
}
lang.rest = function(coll) {
return coll.seq().rest();
}
lang.seq = function(coll) {
if (lang.isNil(coll)) return null;
if (coll["seq"]) return coll.seq();
if (lang.isNumber(coll)) throw "not seqable";
if ("length" in coll) return new lang.ArraySeq(coll, 0);
if (lang.isFunction(coll)) throw "not seqable";
return new lang.ArraySeq(lang.objectToArray(coll), 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment