zoukankan      html  css  js  c++  java
  • [Functional Programming] Transition State based on Existing State using the State ADT (liftState, composeK)

    While sometimes outside input can have influence on how a given stateful transaction transitions, there are many times where the current state at the time of a transaction. We can see the power of this type of transaction by seeing what it would take to read from two different locations in state in parallel and then pass on the result of combining them under a comparison operation to another transition that will set a different location based on the result.

    const {prop, State, omit, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
    const  {get, modify, of} = State; 
    
    // getState :: String -> State Object (Maybe a)
    const getState = key => get(prop(key));
    
    // liftState :: ( a -> b) -> a -> State s b
    const liftState = fn => compose(
        of,
        fn // getfn return value and pass into State.of
    );
    
    // getHint :: () -> State AppState Hint 
    const getHint = () => getState('hint')
        .map(option({color: 'yay', shape: 'uwu'}));
    
    // getCard :: String -> State AppState Card
    const getCard = (id) => getState('cards')
        .map(chain(find(propEq('id', id)))) // find() return a Maybe, so need to use chain to unfold the value
        .map(option({id: null, color: 'unk', shape: 'unk'}));
    
    // cardToHint :: State AppState Hint     
    const cardToHint = composeK(
        liftState(omit(['id'])),
        getCard
    )
    
    // setIsCorrect :: Boolean -> State AppState ()    
    const setIsCorrect = (b) => modify(mapProps({'isCorrect': constant(b)}));
    
    const validateAnswer = converge(
        liftA2(equals),
        cardToHint,
        getHint
    )
    
    const feedback = composeK(
        setIsCorrect,
        validateAnswer
    )
    
    
    /////////////////////////////////////////////////////
    
    const state = {
        cards: [
            {id: 'green-square', color: 'green', shape: 'square'},
            {id: 'orange-square', color: 'orange', shape: 'square'},
            {id: 'blue-triangle', color: 'blue', shape: 'triangle'}
        ],
        hint: {
            color: 'green',
            shape: 'square'
        },
        isCorrect: null
    }
    
    console.log(
        feedback('green-square')
            .execWith(state)
    )
    
    
  • 相关阅读:
    duilib框架分析:几个回调(C++11)
    duilib框架分析(一)概述
    图解JVM--(二)垃圾回收
    图解jvm--(一)jvm内存结构
    4 (计算机网络) DHCP与PXE:IP是怎么来的,又是怎么没的?
    3(计算机网络)ifconfig:最熟悉又陌生的命令行
    2 (计算机网络)理解网络协议的工作模式
    1 (计算机网络)我们常用的网络协议有哪些?
    阿里云配置mysql
    深入Spring Boot:那些注入不了的Spring占位符(${}表达式)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10257131.html
Copyright © 2011-2022 走看看