[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: ,
left: ,
moves:
}
const inc = x => x + ;
const dec = x => x - ;
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(, );
const over = (key, fn) => modify(mapProps({[key]: fn}))
const getState = key => get(prop(key));
const liftState = fn => compose(
of,
fn
)
const limitMoves = clampAfter(, );
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
)
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 };
---
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');
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: ,
left: ,
moves:
}
const inc = x => x + ;
const dec = x => x - ;
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(, );
const over = (key, fn) => modify(mapProps({[key]: fn}))
const getState = key => get(prop(key));
const liftState = fn => compose(
of,
fn
)
const limitMoves = clampAfter(, );
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
)
// 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); 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 }; const sillyVerb = createAction('SILLY_VERB'); console.log(
reducer(
state,
selectCardAction('green-square')
)
)
[Functional Programming ADT] Create State ADT Based Reducers (applyTo, Maybe)的更多相关文章
- [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 qu ...
- [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 on ...
- [React + Functional Programming ADT] Connect State ADT Based Redux Actions to a React Application
With our Redux implementation lousy with State ADT based reducers, it is time to hook it all up to a ...
- [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 porti ...
- [Functional Programming] Reader with Async ADT
ReaderT is a Monad Transformer that wraps a given Monad with a Reader. This allows the interface of ...
- [Functional Programming] Introduction to State, thinking in State
Recently, I am learning Working with ADT. Got some extra thought about State Monad. Basiclly how to ...
- [Functional Programming Monad] Substitute State Using Functions With A State Monad (get, evalWith)
We take a closer look at the get construction helper and see how we can use it to lift a function th ...
- [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer
With a well defined demarcation point between Redux and our State ADT based model, hooking up to a R ...
- [Functional Programming ADT] Combine Multiple State ADT Based Redux Reducers
Redux provides a convenient helper for combining many reducers called combineReducer, but it focuses ...
随机推荐
- javascript大神修炼记(1)——入门介绍
读者朋友们好,从今天开始,我将带领新朋友们,从了解javascript开始,一步一步地进阶到大神境界,别的不废话,现在开始,我们就一点一点地从入门阶段开始. 我们还是介绍一下javascript的身世 ...
- LoadRunner中进程运行和线程运行区别
LoadRunner中的进程与线程 1.进程与线程的区别: 进程和线程的区别是什么?进程和线程都是由操作系统所体会的程序运行的基本单元,系统利用该基本单元实现系统对应用的并发性.进程和线程的区别 ...
- python模式匹配,提取指定字段
re匹配时分多行模式(re.M)与单行模式(rs.S),多行模式是每一行单独匹配,单行模式是把所有的行当成一行来匹配. 单行模式下.可以匹配换行符. ^$匹配所有字符 import re s='1_2 ...
- Java网络编程一
1.InetAddress的应用 import java.util.List; import java.math.BigDecimal; import java.net.InetAddress; im ...
- CodeForces 143C Help Farmer
暴力枚举. 枚举最小的那个数字,不会超过$1000$,剩下的两个数字根号的效率枚举一下即可. #include<bits/stdc++.h> using namespace std; lo ...
- 29、Flask实战第29天:cms用户名渲染和注销功能实现
这节来完成用户名渲染和注销的功能,目前用户名在前端页面是写死的,我们需要动态的展示出来 用户名渲染 实现用户名动态展示,其中一种方法就是在视图函数,根据session信息,获取到user id,通过该 ...
- 通过邮箱验证注册——.net代码
在写一些面向用户的网站类的程序时,必不可少的一个就是注册,通常情况下,我们会选择邮箱验证后注册,或者手机发送验证码注册.上篇文章中已经简单的描述了手机验证注册,这篇主要介绍一下邮箱验证. 邮箱验证的步 ...
- [Atcoder Grand Contest 004] Tutorial
Link: AGC004 传送门 A: …… #include <bits/stdc++.h> using namespace std; long long a,b,c; int main ...
- 2017 ACM-ICPC ECFINAL过山车体验
这次采用domjudge判题,算是比较好玩的啦.外榜地址:http://board.acmicpc.cn/ 然后我们很可惜地止步于192名QAQ,没看出C是个傻逼题,没读懂B..我得背锅,亏我还打了那 ...
- luogu 6月月赛 E 「数学」约数个数和
题面在这里! 第一眼感觉炒鸡水啊...只要把N质因数分解一下,因为k次约数相当于求k+2元一次方程的非负整数解,所以答案就是和每个质因子指数有关的一些组合数乘起来. 但是要用pillard's rho ...