[Functional Programming Moand] Update The State Of A State Monad (put)


Stateful computations require the ability for their state to change overtime. We take a look on one way to replace the state portion of our stateful datatype with a value. We explore the mechanics of how this can be accomplished and introduce theputconstruction helper. We also see how we can run our instances withexecWithto extract the state portion and discard the resultant.

Put state is replace the old state with new state:

//putState :: s -> State s ()
const putState = state => State(() => Pair(Unit(), state));
console.log(
    putState('new')
        .runWith('OLD') //Pair( (), "put" )
)

This is useful when we want to create 'reset':

//putState :: s -> State s ()
const putState = state => State(() => Pair(Unit(), state));
//reset :: () -> State String ()
const reset = () => putState('default');
console.log(
    reset()
        .execWith('OLD') // default
)

This opreation is commonly used, therefore there is a well made function 'put':

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

const { put, get } = State;

//reset :: () -> State String ()
const reset = () => put('default');
console.log(
    reset()
        .execWith('OLD') // default
)
console.log(
    put('new')
        .runWith('OLD') //Pair( (), "new" )
)

优质内容筛选与推荐>>
1、找房子兼郁闷-我什么时候能整这一河滩人写代码
2、Day1:注释
3、python+scrapy+selenium爬虫
4、字符串与正则表达式
5、我的作品02-1


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn