[Functional Programming ADT] Create State ADT Based Reducers (applyTo, Maybe)

The typical Redux Reducer is function that takes in the previous state and an action and uses a switch case to determine how to transition the provided State. We can take advantage of the Action Names being Strings and replace the typical switch case with a JavaScript Object that pairs our State ADT reducers with their actions.

We can also take care of the case in which a reducer does not have an implementation for a given action, by reaching for the Maybe data type and updating our main Redux reducer to handle the case for us, by providing the previous state untouched. And all of this can be captured in a simple helper function we can use in all of our reducer files.

 

This post will focus on how to do reducer pattern, not the functionalities details, all the functionalities codes are listed here:

复制代码
const {prop, isSameType, State, when, assign, 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: 4,
    left: 8,
    moves: 0
}
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 limitMoves = clampAfter(0, 8);
const decLeft = () => over("left", limitMoves(dec));
const incMoves = () => over("moves", limitMoves(inc));
const assignBy = (pred, obj) =>
  when(pred, assign(obj));
const applyMove =
  composeK(decLeft, incMoves)

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
)
const validateAnswer = converge(
    liftA2(equals),
    cardToHint,
    getHint
)
const setIsCorrect = b => over('isCorrect', constant(b));
const adjustRank = compose(limitRank, incOrDec);
const updateRank = b => over('rank', adjustRank(b));
const applyFeedback = converge(
    liftA2(constant),
    setIsCorrect,
    updateRank
)
const markSelected = id =>
  assignBy(propEq('id', id), { selected: true })
const selectCard = id =>
  over('cards', map(markSelected(id)))
const answer = composeK(
    applyMove,
    selectCard
) 
const feedback = composeK(
    applyFeedback,
    validateAnswer
)
View Code
复制代码

 

For now, the reducer pattern was implemented like this:

复制代码
// Action a :: {type: string, payload: a}
// createAction :: String -> a -> Action a
const createAction = type => payload => ({type, payload});
const SELECT_CARD = 'SELECT_CARD';
const SHOW_FEEDBACK = 'SHOW_FEEDBACK';
const selectCardAction = createAction(SELECT_CARD);
const showFeedbackAction = createAction(SHOW_FEEDBACK);

// reducer :: (State, a) -> (State AppState ()) | Null
const reducer = (prevState, {type, payload}) => {
    let result;
    switch(type) {
        case SELECT_CARD:
            result = answer(payload);
            break;
        case SHOW_FEEDBACK:
            result = feedback(payload);
            break;            
        default: 
            result = null;   
    }

    return isSameType(State, result) ? result.execWith(prevState): prevState;
}

console.log(
    reducer(
        state,
        showFeedbackAction('green-square')
    )
)
复制代码

 

Instead of using 'Switch', we can use Object to do the reducer:

复制代码
const actionReducer= {
    SELECT_CARD: answer,
    SHOW_FEEDBACK: feedback
}

const turn = ({type, payload}) => (actionReducer[type] || Function.prototype)(payload);

const reducer = (prevState, action) => {
    const result = turn(action);
    return isSameType(State, result) ? result.execWith(prevState) : prevState;
}
复制代码

'Function.prototype' makes sure that it always return a function can accept payload as param, just it do nothing and return undefined.

 

And code:

(actionReducer[type] || Function.prototype)

it is prefect for Maybe type, so we can continue with refactoring with Maybe:

const createReducer = actionReducer => ({type, payload}) => 
    prop(type, actionReducer)  // safe check type exists on actionReducer
        .map(applyTo(payload)) // we get back a function need to call with payload, using applyTo 
const turn = createReducer({
    SELECT_CARD: answer,
    SHOW_FEEDBACK: feedback
}) 
const reducer = (prevState, action) => {
    return turn(action)
        .chain(safe(isSameType(State))) // check result is the same type as State
        .map(execWith(prevState))       // run with execWith
        .option(prevState);             // unwrap Just and provide default value
    
};

 

---

 

复制代码
  1 const {prop, execWith, applyTo, isSameType, State, when, assign, omit, curry, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
  2 const  {get, modify, of} = State; 
  3 
  4 const state = {
  5     cards: [
  6         {id: 'green-square', color: 'green', shape: 'square'},
  7         {id: 'orange-square', color: 'orange', shape: 'square'},
  8         {id: 'blue-triangle', color: 'blue', shape: 'triangle'}
  9     ],
 10     hint: {
 11         color: 'green',
 12         shape: 'square'
 13     },
 14     isCorrect: null,
 15     rank: 4,
 16     left: 8,
 17     moves: 0
 18 }
 19 const inc = x => x + 1;
 20 const dec = x => x - 1;
 21 const incOrDec = b => b ? dec :  inc;
 22 const clamp = (min, max) => x => Math.min(Math.max(min, x), max);
 23 const clampAfter = curry((min, max, fn) => compose(clamp(min, max), fn))
 24 const limitRank = clampAfter(0, 4);
 25 const over = (key, fn) => modify(mapProps({[key]: fn}))
 26 const getState = key => get(prop(key));
 27 const liftState = fn => compose(
 28     of,
 29     fn
 30 )
 31 const limitMoves = clampAfter(0, 8);
 32 const decLeft = () => over("left", limitMoves(dec));
 33 const incMoves = () => over("moves", limitMoves(inc));
 34 const assignBy = (pred, obj) =>
 35   when(pred, assign(obj));
 36 const applyMove =
 37   composeK(decLeft, incMoves)
 38 
 39 const getCard = id => getState('cards')
 40     .map(chain(find(propEq('id', id))))
 41     .map(option({}))
 42 const getHint = () => getState('hint')
 43     .map(option({}))
 44 const cardToHint = composeK(
 45     liftState(omit(['id'])),
 46     getCard
 47 )
 48 const validateAnswer = converge(
 49     liftA2(equals),
 50     cardToHint,
 51     getHint
 52 )
 53 const setIsCorrect = b => over('isCorrect', constant(b));
 54 const adjustRank = compose(limitRank, incOrDec);
 55 const updateRank = b => over('rank', adjustRank(b));
 56 const applyFeedback = converge(
 57     liftA2(constant),
 58     setIsCorrect,
 59     updateRank
 60 )
 61 const markSelected = id =>
 62   assignBy(propEq('id', id), { selected: true })
 63 const selectCard = id =>
 64   over('cards', map(markSelected(id)))
 65 const answer = composeK(
 66     applyMove,
 67     selectCard
 68 ) 
 69 const feedback = composeK(
 70     applyFeedback,
 71     validateAnswer
 72 )
 73 // Action a :: {type: string, payload: a}
 74 // createAction :: String -> a -> Action a
 75 const createAction = type => payload => ({type, payload});
 76 const SELECT_CARD = 'SELECT_CARD';
 77 const SHOW_FEEDBACK = 'SHOW_FEEDBACK';
 78 const selectCardAction = createAction(SELECT_CARD);
 79 const showFeedbackAction = createAction(SHOW_FEEDBACK);
 80 
 81 const createReducer = actionReducer => ({type, payload}) => 
 82     prop(type, actionReducer)  // safe check type exists on actionReducer
 83         .map(applyTo(payload)) // we get back a function need to call with payload, using applyTo 
 84 const turn = createReducer({
 85     SELECT_CARD: answer,
 86     SHOW_FEEDBACK: feedback
 87 }) 
 88 
 89 const reducer = (prevState, action) => {
 90     return turn(action)
 91         .chain(safe(isSameType(State))) // check result is the same type as State
 92         .map(execWith(prevState))       // run with execWith
 93         .option(prevState);             // unwrap Just and provide default value
 94     
 95 };
 96 
 97 const sillyVerb = createAction('SILLY_VERB');
 98 
 99 console.log(
100     reducer(
101         state,
102         selectCardAction('green-square')
103     )
104 )
复制代码

 

posted @   Zhentiw  阅读(375)  评论(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-02-05 [Javascirpt] Developer-friendly Flow Charts with flowchart.js
2018-02-05 [TS] Class Properties Public, Private and Read Only Modifiers
2018-02-05 [Python + Unit Testing] Write Your First Python Unit Test with pytest
2018-02-05 [React] React.PureComponent
2017-02-05 [Angular] Organizing Your Exports with Barrels
2016-02-05 [Redux] Passing the Store Down Implicitly via Context
2016-02-05 [Redux] Passing the Store Down Explicitly via Props
点击右上角即可分享
微信分享提示