[Functional Programming 101] Crocks.js -- when to use map and when to use chain?

本文通过实例对比了Crocks.js库中.map和.chain方法的使用场景。.map适用于将纯函数应用于状态,而.chain则用于状态转换函数。通过多次调用这两种方法,可以观察到最终状态或结果值的不同获取方式。

As a beginner of Crocks.js, it was a problem for we to figure out when to use .map() and when to use .chain().

 

Of course, using the docs help:

map: State s a ~> (a -> b) -> State s b

chain: State s a ~> (a -> State s b) -> State s b

 

The main difference is that, when using .map(fn), the param is a function.

 For exmaple:  addOne is just a plain function.

const addOne = x => x + 1;

 

When using .chian(sfn), the param is a State(fn)

For example: modify return a state() and inside state(), we apply function addOne.

const modifyOne = () => modify(mapProps({'moves', addOne}));

 

Now, we are going to write two example, one is using .map() another one is using .chain() to achieve the same result.

// We want to get final result as {moves: 4}
const state = {
    moves: 1
}

.chain():

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

const { modify, get } = State;

const getState = key => get(prop(key));

const addOne = x => x + 1;

const modifyOne = () => over('moves', addOne);

const over = (key, fn) => modify(mapProps({[key]: fn}))

const state = {
    moves: 1
}

const getMoves = () => getState('moves').map(option(0))

console.log(
    getMoves()
        .chain(modifyOne)
        .chain(modifyOne)
        .chain(modifyOne)
        .execWith(state) // {moves: 4}
)

Notice that 'getMoves' and 'modifyOne' both return State(), so they have to use .chian().

 

.map():

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

const { modify, get } = State;

const getState = key => get(prop(key));

const addOne = x => x + 1;

const state = {
    moves: 1
}

const getMoves = () => getState('moves').map(option(0))

console.log(
    getMoves()
        .map(addOne)
        .map(addOne)
        .map(addOne)
        .evalWith(state) // 4
)

Since 'addOne' is just a function, we can use .map() instead of .chian(). And more important, we have to use 'evalWith' to get result value, since we are not using 'modify' to change the state.

转载于:https://www.cnblogs.com/Answer1215/p/10310202.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值