加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[Functional Programming Monad] Apply Stateful Computations T

发布时间:2020-12-14 05:12:39 所属栏目:大数据 来源:网络整理
导读:When building our stateful computations,there will come a time when we’ll need to combine two or more state transactions at the same time to come up with a new result. Usually this occurs when want to use plain ol’ JavaScript functions w

When building our stateful computations,there will come a time when we’ll need to combine two or more state transactions at the same time to come up with a new result. Usually this occurs when want to use plain ol’ JavaScript functions with two or more a arguments as part of our stateful computations.

We first look at how this can be accomplished by using?chain?and closure to get access to both functions. Then we will explore how we can leverage the?of?construction helper and the?ap?Stateinstance method to clean this type of interaction up a bit. We then conclude with an even cleaner approach that takes full advantage of a?crocks?helper function named?liftA2.

?

For example,we have a function:

const namefiy = firstName => lastName => `${lastName},${firstName}`;

It should receive two params to return a string.

?

one way is using .ap(),it takes the same input,run with the given functions and return its value,then combine those:

var _getFullName = State.of(namefiy)
    .ap(getFirstName)
    .ap(getLastName)

?

Or we can use .liftA2,it lift the function into State automaticlly:

var getFullName = liftA2(
    namefiy,getFirstName,getLastName
)

?

----

?

const { liftA2,composeK,Unit,curry,objOf,compose,State,mapProps,prop,option } = require("crocks");

const { put,get,modify } = State;

const namefiy = firstName => lastName => `${lastName},${firstName}`;
const getWord = number => name  => name.split( )[number];

const getFirstName = get(getWord(0));
const getLastName = get(getWord(1));

var _getFullName = State.of(namefiy)
    .ap(getFirstName)
    .ap(getLastName)

var getFullName = liftA2(
    namefiy,getLastName
)
console.log(
    getFullName
        .evalWith("John Green")
)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读