Skip to content

Instantly share code, notes, and snippets.

@y-yu
Created November 19, 2014 10:38
Show Gist options
  • Save y-yu/47e864746cc7a8fa06c6 to your computer and use it in GitHub Desktop.
Save y-yu/47e864746cc7a8fa06c6 to your computer and use it in GitHub Desktop.
LazyList
enum StreamCell<T> {
Cons(x : T, t : Stream<T>) : StreamCell<T>;
Nil : StreamCell<T>;
}
typedef Stream<T> = Void -> StreamCell<T>
class LazyList<T> {
private var body : Stream<T>;
private static var nil = function () : StreamCell<T> {
return Nil;
};
public function new(?s : Stream<T>) {
s == null ? this.body = nil : this.body = s;
}
public inline function cons(x : T) : LazyList<T> {
var s = this.toStream();
this.body = function() : StreamCell<T> {
return Cons(x, s);
};
return this;
}
public inline function hd() : T {
return switch(this.body()) {
case Nil: null;
case Cons(h, _): h;
}
}
public inline function tl() : LazyList<T> {
return switch(this.body()) {
case Nil: new LazyList();
case Cons(_, t): new LazyList(t);
}
}
public inline function append(a : LazyList<T>) : LazyList<T> {
function loop (x : Stream<T>, y : Stream<T>) : Stream<T> {
return switch (x()) {
case Nil: y;
case Cons(h, t): function () : StreamCell<T> {
return Cons(h, loop(t, y));
};
};
}
return new LazyList( loop(this.body, a.body) );
}
public inline function reverse() : LazyList<T> {
function rev(s : Stream<T>, a : Stream<T>) : Stream<T> {
return switch(s()) {
case Nil : a;
case Cons(h, t):
rev(t, function () { return Cons(h, a); } );
}
}
return new LazyList(rev(this.body, nil));
}
public inline function toStream() : Stream<T> {
return this.body;
}
public inline function toArray() : Array<T> {
function loop(s : Stream<T>) {
return switch(s()) {
case Nil: [];
case Cons(h, t): [h].concat(loop(t));
};
}
return loop(this.body);
}
}
class Test {
static function main() {
var x = (new LazyList<Int>()).cons(2).cons(1);
var y = (new LazyList<Int>()).cons(4).cons(3);
var z = x.append(y);
trace(z.reverse().hd());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment