zoukankan      html  css  js  c++  java
  • [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()

    One important thing to take away, to make it lazy, wrap into a function

  • 相关阅读:
    590. N 叉树的后序遍历
    CF605E
    网络流水题题单
    wqs二分的边界
    luoguP6326 Shopping
    【THUWC2020】工资分配
    CF1336简要题解
    「PKUWC2020」最小割
    洛谷P4895 独钓寒江雪
    省选联考2020简要题解
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6193692.html
Copyright © 2011-2022 走看看