zoukankan      html  css  js  c++  java
  • [Functional Programming] Compose Simple State ADT Transitions into One Complex Transaction

    State is a lazy datatype and as such we can combine many simple transitions into one very complex one. This gives us a lot of control over how our state changes over time. In this lesson we will use this to our advantage and combine many transactions into one complex action. In the end only the final state will be reported which can be reasoned about as one transition.

    const state = {
        cards: [
            {id: 'green-square', color: 'green', shape: 'square'},
            {id: 'orange-square', color: 'orange', shape: 'square'},
            {id: 'blue-square', color: 'blue', shape: 'triangle'}
        ],
        left: 8,
        moves: 0
    }
    
    const {State, when, assign, map, mapProps, propEq, curry, compose} = require('crocks');
    const {modify} = State;
    
    const inc = x => x + 1;
    const dec = x => x - 1;
    
    const clamp = (min, max) => x => Math.min(Math.max(min, x), max);
    const clampAfter = curry((min, max, fn) =>
      compose(
        clamp(min, max),
        fn
      )
    );
    
    const limitMoves = clampAfter(0, 8);
    
    const decLeft = () => over("left", limitMoves(dec));
    const incMoves = () => over("moves", limitMoves(inc));
    
    
    
    const markSelected = id => assignBy(propEq('id', id), {selected: true})
    const assignBy = (pred, obj) => when(pred, assign(obj));
    const over = (key, fn) => modify(mapProps({ [key]: fn }));
    
    const selectCard = id => over('cards', map(markSelected(id)))
    
    const answer = (id) => State.of(id)
        .chain(incMoves)
        .chain(incMoves)
        .chain(decLeft)
        .chain(selectCard);
    
    
    console.log(
        JSON.stringify(
            answer('green-square').execWith(state),
            null,
            2
        )
    ); 
     /*
    {
      "cards": [
        {
          "id": "green-square",
          "color": "green",
          "shape": "square"
        },
        {
          "id": "orange-square",
          "color": "orange",
          "shape": "square"
        },
        {
          "id": "blue-square",
          "color": "blue",
          "shape": "triangle"
        }
      ],
      "left": 7,
      "moves": 2
    }
    */
  • 相关阅读:
    事务与数据库连接池DBCP和C3P0与工具类DBUtils
    JavaWeb基础JSP页面EL 和JSTL表达式
    Cookie和Session
    HttpServletRequest 和HttpServletResponse
    Http协议和Servlet
    Xml 和Tomcat
    Struts2第二天:Struts2的数据的封装、结果页面配置
    BootStrap基础知识总结
    Linux和Windows下Mysql数据库安装详解
    CSS 边框
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10241541.html
Copyright © 2011-2022 走看看