首页 > 代码库 > [Compose] 9. Delay Evaluation with LazyBox
[Compose] 9. Delay Evaluation with LazyBox
We rewrite the Box example using lazy evaulation.
Here is Box example:
const Box = (x) => ({ map: f => Box(f(x)), fold: f => f(x)});const res = Box(‘ 64 ‘) .map(abba => abba.trim()) .map(trimmed => new Number(trimmed)) .map(number => number + 1) .map(x => String.fromCharCode(x)) .fold(x => x.toLowerCase());console.log(res); // ‘a‘
So how to make it as Lazy Box? The Answer is instead of passing a value to the Box, we pass and function into it.
const LazyBox = (fn) => ({ map: g => LazyBox(() => g(fn())), fold: g => g(fn()) // call the g()});const res = LazyBox(() => ‘ 64 ‘) .map(abba => abba.trim()) .map(trimmed => new Number(trimmed)) .map(number => number + 1) .map(x => String.fromCharCode(x)) .fold(x => x.toLowerCase());console.log(res); // ‘a‘
inside map function, we use function defination:
() => g(fn())
Just defined, but not call. Using g() is to make it composeable.
When actually ‘fold‘, we call fn():
fold: g => g(fn()) // call the g()
[Compose] 9. Delay Evaluation with LazyBox
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。