, , .
, thunk, .. Lazy , .
join - , , , ! , , ; , .
return ( of ) ; return , .. Lazy.of(2) Lazy($ => 2)
, , . , ^ _ ^ , Lazy . runLazy. < 3
thunks $ => expr () => expr. JavaScript () s, (), . , Lazy($ => f()) ( ) , Lazy(() => f()). , , . , , .
, , () $ . ...
const Lazy = t => ({
memo: undefined,
runLazy () {
return this.memo === undefined
? (this.memo = t(), console.log('computed:', this.memo), this.memo)
: this.memo
},
chain (f) {
return Lazy($ => f(this.runLazy()).runLazy())
}
})
Lazy.of = x =>
Lazy($ => x)
const repeat = n => f => x =>
n === 0
? Lazy.of(x)
: Lazy.of(f(x)).chain(repeat (n-1) (f))
const m = repeat (5) (x => x * 2) (1)
console.log('computations pending...')
console.log(m.runLazy())
console.log(m.runLazy())
Hide result, Lazy. Monoid empty, , , - - !
, chain f => join(map(f)), .
Functor
map (f) {
return Lazy($ => f(this.runLazy()))
}
const apply = f => x => f (x)
ap (m) {
return Lazy($ => apply (this.runLazy()) (m.runLazy()))
}
Lazy.of = x =>
Lazy($ => x)
chain (f) {
return Lazy($ => f(this.runLazy()).runLazy())
}
join () {
return Lazy($ => this.runLazy().runLazy())
}
Monoid
empty () {
}
concat (m) {
return Lazy($ => this.runLazy().concat(m.runLazy()))
}
, , , , /. !