[Functional Programming] Combine Multiple State ADT Instances with the Same Input (converge(liftA2(constant)))

When combining multiple State ADT instances that depend on the same input, using chain can become quite burdensome. We end up having to play leapfrog with values inside of nested chain statements. Very reminiscent of the old callback nastiness we had to deal with before Promisesgraced our existence.

But fear not, but taking advantage of the Applicative Functor portion of the State ADT in combination with the converge combinator, we can apply these types of transitions in unison, passing the value to both virtually simultaneously.

 

For example:

// () -> b
const validateAnswer = converge(
    liftA2(equals),
    cardToHint,
    getHint
)

'validateAnswer' return a boolean value.

 

We want to take this value, and pass to two functions 'setIsCorrect' & 'updateRank'

// b -> ()
const setIsCorrect = b => over('isCorrect', constant(b));

// b -> ()
const updateRank = b => over('rank', adjustRank(b));

 

One functional way to do this is using 'converge':

const applyFeedback = converge(
    liftA2(constant),
    setIsCorrect,
    updateRank
)

 

----------------

复制代码
const {prop, State, omit, curry, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
const  {get, modify, of} = State; 

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,
    rank: 2
}

const inc = x => x + 1;
const dec = x => x - 1;
const incOrDec = b => b ? dec :  inc;
const clamp = (min, max) => x => Math.min(Math.max(min, x), max);
const clampAfter = curry((min, max, fn) => compose(clamp(min, max), fn));
const limitRank = clampAfter(0, 4);
const over = (key, fn) => modify(mapProps({[key]: fn}))
const getState = key => get(prop(key));
const liftState = fn => compose(
    of,
    fn
)
const getCard = id => getState('cards')
    .map(chain(find(propEq('id', id))))
    .map(option({}))
const getHint = () => getState('hint')
    .map(option({}))
const cardToHint = composeK(
    liftState(omit(['id'])),
    getCard
)
// () -> b
const validateAnswer = converge(
    liftA2(equals),
    cardToHint,
    getHint
)
// b -> ()
const setIsCorrect = b => over('isCorrect', constant(b));

const adjustRank = compose(limitRank, incOrDec);
// b -> ()
const updateRank = b => over('rank', adjustRank(b));

const applyFeedback = converge(
    liftA2(constant),
    setIsCorrect,
    updateRank
)

const feedback = composeK(
    applyFeedback,
    validateAnswer
)

console.log(
    feedback('green-square')
        .execWith(state)
)
复制代码

 

posted @   Zhentiw  阅读(175)  评论(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-14 [ES6] Generators
2016-01-14 [ES6] ITERATORS
2016-01-14 [ES6] Promise
2016-01-14 [ES6] Export class and variable
2016-01-14 [ES6] Module export
2016-01-14 [ES6] Class Inherit
2016-01-14 [ES6] Set && WeakSet
点击右上角即可分享
微信分享提示