[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
}
*/
复制代码

 

posted @   Zhentiw  阅读(118)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-01-08 [Python] Use a Python Generator to Crawl the Star Wars API
点击右上角即可分享
微信分享提示