Last active
December 20, 2015 17:54
-
-
Save jooyunghan/dfdc73282c6437bc0c11 to your computer and use it in GitHub Desktop.
lazy in 'even' style.
This file contains hidden or 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
// http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#lazyinstrict | |
class Cons<A, B> { | |
head: A; | |
tail: B; | |
constructor(head: A, tail: B) { | |
this.head = head; | |
this.tail = tail; | |
} | |
} | |
function cons<A, B>(head: A, tail: B): Cons<A, B> { | |
return new Cons(head, tail); | |
} | |
// --- | |
class Susp<T> { | |
gen: () => T; | |
value: T; | |
constructor(gen: () => T) { | |
this.gen = gen; | |
} | |
force(): T { | |
if (this.gen) { | |
this.value = this.gen(); | |
this.gen = null; | |
} | |
return this.value; | |
} | |
} | |
// --- | |
class Stream<A> extends Susp<Cons<A, Stream<A>>> { | |
constructor(s) { | |
super(s); | |
} | |
} | |
// --- | |
function map<A,B>(f: (A)=>B, s: Stream<A>): Stream<B> { | |
return new Stream<B>(() => { | |
var s_ = s.force(); | |
if (s_ === null) { | |
return null; | |
} else { | |
return cons(f(s_.head), map(f, s_.tail)); | |
} | |
}); | |
} | |
function countdown(n: number): Stream<number> { | |
return new Stream<number>(() => cons(n, countdown(n-1))); | |
} | |
function cutoff<A>(n: number, s: Stream<A>): Array<A> { | |
if (n === 0) { | |
return []; | |
} else { | |
var s_ = s.force(); | |
if (s_ === null) { | |
return []; | |
} else { | |
return [s_.head].concat(cutoff(n - 1, s_.tail)); | |
} | |
} | |
} | |
function sqrt(n: number): number { | |
if (n < 0) throw new Error("negative"); | |
return Math.sqrt(n); | |
} | |
console.log(cutoff(5, map(sqrt, countdown(4)))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment