首页 > 其他 > 详细

[Compose] 9. Delay Evaluation with LazyBox

时间:2016-12-18 09:54:04      阅读:185      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/Answer1215/p/6193692.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!