zoukankan      html  css  js  c++  java
  • [Functional Programming 101] Crocks.js -- when to use map and when to use 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.

  • 相关阅读:
    mysql修改登录密码三种方式
    python 面向对象类与类之间的关系
    python 初识函数
    python 编码
    MVC部门树的实现 http://www.ztree.me/v3/api.php
    事务能否对一个表进行如下操作:先删除后添加?
    添加注释时,该如何输入当前修改时间呢
    js代码折叠的方法//#region 代码 //#endregion
    echarts画折线图,柱状图,饼图
    方法中开启一个事务之后,能否调用另一个通过事务实现的函数?
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10310202.html
Copyright © 2011-2022 走看看