zoukankan      html  css  js  c++  java
  • [Functional Programming Monad] Combine Stateful Computations Using A State Monad

    The true power of the State ADT really shows when we start combining our discrete, stateful transactions. We start looking at another construction helper named of, used to lift any given value of any type into the resultant. We also explore another instance method called chain that is used for combining our simple, discrete transactions into more complex flows that can be extended to meet our needs as they arise. To create a set of stateful transactions to be combined, we see how the get and modify construction helpers can be used to make simple, easy to read code.

    const { constant, Pair, Unit, curry, objOf, compose, State, mapProps, prop, option } = require("crocks");
    
    const { put, get, modify } = State;
    
    
    const add = x => y => x+y;
    const inc = add(1);
    
    // State s a -> State(x => Pair(a, x))
    
    // 'get' return result apply to variable a
    const addState = n => 
        get(add(n))
    
    const incState = n => 
        modify(inc) // modify return Unit() in variable position, Pair( (), 3 )
        .map(constant(n)) // to keep the vairable a, we can use constant to wrap a value into function, Pair( 12, 3 )
    
    const compute = n => 
        State.of(n)
            .chain(addState)
            .chain(incState)
    
    
     console.log(
         compute(10)
            .runWith(2)
     )       
  • 相关阅读:
    三大高级排序
    三大初级排序算法
    MVC的JsonResult用法
    使用dynamic类型改进反射
    正则指引-括号(3)反向引用
    正则指引-括号(2)引用分组
    正则指引-括号(1)
    正则指引-量词demo
    正则指引-字符组demo
    ASP.NET MVC 分部视图
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10338745.html
Copyright © 2011-2022 走看看