zoukankan      html  css  js  c++  java
  • [Functional Programming Monad] Apply Stateful Computations To Functions (.ap, .liftA2)

    When building our stateful computations, there will come a time when we’ll need to combine two or more state transactions at the same time to come up with a new result. Usually this occurs when want to use plain ol’ JavaScript functions with two or more a arguments as part of our stateful computations.

    We first look at how this can be accomplished by using chain and closure to get access to both functions. Then we will explore how we can leverage the of construction helper and the ap Stateinstance method to clean this type of interaction up a bit. We then conclude with an even cleaner approach that takes full advantage of a crocks helper function named liftA2.

    For example, we have a function:

    const namefiy = firstName => lastName => `${lastName}, ${firstName}`;

    It should receive two params to return a string.

    one way is using .ap(), it takes the same input, run with the given functions and return its value, then combine those:

    var _getFullName = State.of(namefiy)
        .ap(getFirstName)
        .ap(getLastName)

    Or we can use .liftA2, it lift the function into State automaticlly:

    var getFullName = liftA2(
        namefiy,
        getFirstName,
        getLastName
    )

    ----

    const { liftA2, composeK, Unit, curry, objOf, compose, State, mapProps, prop, option } = require("crocks");
    
    const { put, get, modify } = State;
    
    const namefiy = firstName => lastName => `${lastName}, ${firstName}`;
    const getWord = number => name  => name.split(' ')[number];
    
    const getFirstName = get(getWord(0));
    const getLastName = get(getWord(1));
    
    var _getFullName = State.of(namefiy)
        .ap(getFirstName)
        .ap(getLastName)
    
    var getFullName = liftA2(
        namefiy,
        getFirstName,
        getLastName
    )
    console.log(
        getFullName
            .evalWith("John Green")
    )
  • 相关阅读:
    [ARC074C] RGB Sequence
    [SHOI2014] 概率充电器
    CF368B Sereja and Suffixes
    CF980D Perfect Groups
    Rainbow Roads(gym101617G)(DFS序,差分)
    Educational Codeforces Round 104 (Rated for Div. 2)(A~E)
    Floor and Mod(CF1485C)(数论)
    Longest Simple Cycle(CF1476C)(线性dp)
    Factories(Gym102222G)(树形dp+背包)
    Codeforces Round #699 (Div. 2)(A,B,C,D)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10343548.html
Copyright © 2011-2022 走看看