Skip to content

Instantly share code, notes, and snippets.

@wernerdegroot
Created October 18, 2018 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wernerdegroot/a9bbd38a4e073d10647a884167991d3c to your computer and use it in GitHub Desktop.
Save wernerdegroot/a9bbd38a4e073d10647a884167991d3c to your computer and use it in GitHub Desktop.
Lazy.ts
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