zoukankan      html  css  js  c++  java
  • [Functional Programming Monad] Refactor Stateful Code To Use A State Monad

    When we start to accumulate functions that all work on a given datatype, we end up creating a bunch of boilerplate code in almost every function to handle the changes we need to make to our records’ values. This can lead to not only undesirable boilerplate present in all of our functions, but also can cause us to have to create variables just to manage our stateful changes.

    We’ll take a look at a couple patterns that can act as early warning signs that will eventually cause us to not have a good time. Once we know what the smell is, we’ll look at how moving our computations into State can clean up all of our state management code by making it the responsibility of State. This allows our functions to only describe how state should change over time versus us having to change it ourselves.

    Imaging we have a user object, if we want to udpate firstName prop, we have to update fullName as well.

    const user =  {
        firstName: 'John',
        lastName: 'Green',
        fullName: 'John Green'
    }

    Code like this:

    const _buildFulName = user => {
        const {firstName, lastName} = user;
        const fullName = joinName(firstName, lastName)
        return _updateFullName(fullName, user)
    }
    const _updateFirstName = curry(
        firstName => compose(
            _buildFulName,
            assign({firstName})
        )
    )
    const _updateFullName = curry(
        fullName => assign({fullName})
    )

    We want to use a more flexiable way to do it:

    const getState = (key) => get(prop(key))
    const getFirstName = () => getState('firstName').map(option(''));
    const getLastName = () => getState('lastName').map(option(''));
    const joinName = firstName => lastName =>  `${firstName}, ${lastName}`
    
    const buildFullName = () => liftA2(
        joinName,
        getFirstName(),
        getLastName()
    ).chain(updateFullName)
    const updateFirstName = firstName =>  modify(
        assign({firstName})
    ).chain(buildFullName);
    const updateFullName = fullName =>  modify(
        assign({fullName})
    )
  • 相关阅读:
    求两图的 对比度
    关于opencv中的颜色模型转换之CV_BGR2HSV
    转 C++函数返回值,你必须注意的问题
    opencv 3.2 vs2015 debug assertion __acrt_first_block == header
    vs的【warning C4996:'fopen': This function or variable may be unsafe】解决方案
    c++ opencv 3.2 +Mfc VS2015窗体显示图片方法
    c++中“箭头(->)”和“点号(.)”操作符的区别
    C# devexpress gridcontrol 分页 控件制作
    c#Md5 32位加密结果少了两个0的原因
    opencv 线,椭圆 圆
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10343921.html
Copyright © 2011-2022 走看看