Created
October 18, 2018 09:42
-
-
Save wernerdegroot/a9bbd38a4e073d10647a884167991d3c to your computer and use it in GitHub Desktop.
Lazy.ts
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
type Lazy<A> = () => A | |
const Lazy = { | |
map<A, B>(l: Lazy<A>, fn: (a: A) => B): Lazy<B> { | |
return lazy(() => fn(l())) | |
} | |
} | |
function lazy<A>(fn: () => A): Lazy<A> { | |
let memoized: { value: A } | false = false | |
return (): A => { | |
if (memoized === false) { | |
const value = fn() | |
memoized = { value } | |
return value | |
} else { | |
return memoized.value | |
} | |
} | |
} | |
interface ILazyList<A> { | |
map<B>(fn: (a: A) => B): ILazyList<B> | |
} | |
class LazyCons<A> implements ILazyList<A> { | |
constructor(public readonly head: Lazy<A>, public readonly tail: Lazy<ILazyList<A>>) { } | |
map<B>(fn: (a: A) => B): ILazyList<B> { | |
return new LazyCons<B>( | |
Lazy.map(this.head, fn), | |
Lazy.map(this.tail, nonLazyTail => nonLazyTail.map(fn)) | |
) | |
} | |
} | |
class LazyNil<A> implements ILazyList<A> { | |
map<B>(fn: (a: A) => B): ILazyList<B> { | |
return new LazyNil<B>() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment