[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:
}
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 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)
)
[Functional Programming] Combine Multiple State ADT Instances with the Same Input (converge(liftA2(constant)))的更多相关文章
- [Functional Programming ADT] Combine Multiple State ADT Based Redux Reducers
Redux provides a convenient helper for combining many reducers called combineReducer, but it focuses ...
- [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 ...
- [Functional Programming] Combine State Dependent Transactions with the State ADT (composeK to replace multi chian call)
When developing a Finite State Machine, it is often necessary to apply multiple transitions in tande ...
- [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 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] 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] Reader with Async ADT
ReaderT is a Monad Transformer that wraps a given Monad with a Reader. This allows the interface of ...
- [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 swit ...
- [Functional Programming ADT] Adapt Redux Actions/Reducers for Use with the State ADT
By using the State ADT to define how our application state transitions over time, we clear up the ne ...
随机推荐
- onchange监听input值变化及input隐藏后change事件不触发的原因与解决方法(设置readonly后onchange不起作用的解决方案)
转自:https://www.cnblogs.com/white0710/p/7338456.html 1. onchange事件监听input值变化的使用方法: <input id=" ...
- python数据类型-----列表
今天来总结下python3.4版本列表的一些操作方法. 列表(list): 1.列表就像一个线性容器,但是比C++的 lis t扩展多得多,列表里的元素可以是相同类型,也可以包含各种类型,比如列表里嵌 ...
- 手机端图片插件可缩放 旋转 全屏查看photoswipe
官方介绍PhotoSwipe 是专为移动触摸设备设计的相册/画廊.兼容所有iPhone.iPad.黑莓6+,以及桌面浏览器.底层实现基于HTML/CSS/JavaScript,是一款免费开源的相册产品 ...
- Spring -- 注解事务 以及 7个传播行为
注解事务: 1.开启注解事务配置: <!-- 事务管理器 --> <bean id="transactionManager" class="org.sp ...
- poj 1947(树形DP+背包)
Rebuilding Roads Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 10663 Accepted: 4891 ...
- [jquery] ajax 调试
$.ajax({ type: ‘post’, url: url, data: {code: ‘15′}, dataType: ‘jsonp’, sccuess:function(data){ aler ...
- centos6.5 安装stardict 出现问题 [Errno 256] No more mirrors to try
1. 下载startdict #wget http://downloads.naulinux.ru/pub/NauLinux/6x/i386/sites/School/RPMS/stardict-3. ...
- Codeforces Round #442 A Alex and broken contest【字符串/常量数组/string类】
A. Alex and broken contest time limit per test 2 seconds memory limit per test 256 megabytes input s ...
- 手动安装python3和xgboost
yum install openssl-devel -y .tar.xz cd Python- ./configure --prefix=/usr/local/python3.5.4 make mak ...
- Web应用渗透测试框架Arachni
Web应用渗透测试框架Arachni Arachni是一款Ruby语言编写的Web应用渗透测试框架.当用户指定目标后,该框架可以自动扫描网站页面,对页面中的链接.表单.Cookie.HTTP He ...