[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)
)

复制代码
posted @   Zhentiw  阅读(156)  评论(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工具
历史上的今天:
2017-01-11 [Git] Use git add --patch for better commit history and mitigating bugs
2017-01-11 [ES6] Use ES6 Proxies
2017-01-11 [Javascript] Javascript 'in' opreator
2016-01-11 [React Testing] The Redux Store - Multiple Actions
点击右上角即可分享
微信分享提示