[Functional Programming] Define Discrete State Transitions using the State ADT

We build our first state transactions as two discrete transactions, each working on a specific portion of the state. Each of these transitions are governed by an acceptable range and we want to be able to apply these limit within our model.

With our discrete transactions we see that is easy to reason about and keeps our rules local to the data being worked on, without having to be considered in other transitions or, even worse, in the eventual view layer. Patterns like this make it easier to easily transport a given data model to any view layer.

 

复制代码
const { curry, compose, State, mapProps } = require("crocks");

const { modify } = State;

const state = {
  left: 8,
  moves: 0
};

const inc = x => x + 1;
const dec = x => x - 1;

// Make sure 'x' in range of [min, max]
// if x < min, return min
// if x > max, return max
const limitRange = (min, max) => x => Math.min(Math.max(min, x), max);

// Run the 'fn', get the value, then pass into limitRange
const limitAfter = curry((min, max, fn) =>
  compose(
    limitRange(min, max),
    fn
  )
);

// For each key we passed in, apply fn to it
const over = (key, fn) => modify(mapProps({ [key]: fn }));

const limitMoves = limitAfter(0, 8);

const decLeft = () => over("left", limitMoves(dec));

const res = decLeft()
  .chain(decLeft)
  .execWith(state);
console.log(res); //{left: 6, moves: 0}
复制代码

 

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工具
历史上的今天:
2016-01-07 [React Testing] Children with Shallow Rendering
2016-01-07 [React Testing] Reusing test boilerplate
2016-01-07 [React Testing] Conditional className with Shallow Rendering
2016-01-07 [React Testing] className with Shallow Rendering
2015-01-07 [MODx] 9. Real Example
2015-01-07 [MODx] 8. Snippet get data, chunk display
2015-01-07 [MODx] 7. MIGX DB
点击右上角即可分享
微信分享提示