When developing a Finite State Machine, it is often necessary to apply multiple transitions in tandem. To accomplish this in most Redux work flows requires at best, implementing multiple action handlers in separate reducers; or at worse, the need to duplicate logic for similar action handlers, sometime across multiple files. However when using a State ADT, we can easily combine these independent transitions by simply chain-ing multiple discrete transitions into one transaction. We demonstrate this interface by transitioning two portions of related state with one transaction.

const { curry, compose, State, mapProps, composeK } = require("crocks");

const { modify } = State;

const state = {
left: 8,
moves: 0
}; const inc = x => x + 1;
const dec = x => x - 1; const clamp = (min, max) => x => Math.min(Math.max(min, x), max);
const clampAfter = curry((min, max, fn) =>
compose(
clamp(min, max),
fn
)
);
const over = (key, fn) => modify(mapProps({ [key]: fn })); const limitMoves = clampAfter(0, 8); const decLeft = () => over("left", limitMoves(dec));
const incMoves = () => over("moves", limitMoves(inc)); // Then there are a series of chain functions, using composeK
/**
* replace:
* decLeft()
* .chain(decLeft)
* .chain(decLeft)
* .chain(decLeft)
* .chain(incMoves)
* .chain(incMoves)
*/
const applyMove = composeK(
incMoves, incMoves, decLeft, decLeft, decLeft
) const res = applyMove()
.execWith(state);
console.log(res); //{ left: 5, moves: 2 }

Another example:

const state = {
cards: [
{id: 'green-square', color: 'green', shape: 'square'},
{id: 'orange-square', color: 'orange', shape: 'square'},
{id: 'blue-square', color: 'blue', shape: 'triangle'}
],
left: 8,
moves: 0
} const {State, when, assign, map, mapProps, propEq} = require('crocks');
const {modify} = State; const markSelected = id => assignBy(propEq('id', id), {selected: true})
const assignBy = (pred, obj) => when(pred, assign(obj));
const over = (key, fn) => modify(mapProps({ [key]: fn })); const selectCard = id => over('cards', map(markSelected(id))) console.log(
JSON.stringify(
selectCard('green-square').execWith(state),
null,
2
)
); /*
// Using Ramda to implememnt the same logic
const {compose, map, propOr, when, propEq, mergeLeft} = require('ramda'); const markAsSelected = (id) => when(propEq('id', id), mergeLeft({selected: true}))
const over = (key, fn) => compose(map(fn), propOr([], key)); const selectCard2 = (id) => over('cards', markAsSelected(id)) console.log(
JSON.stringify(
selectCard2('green-square')(state),
null,
2
)
)*/

[Functional Programming] Combine State Dependent Transactions with the State ADT (composeK to replace multi chian call)的更多相关文章

  1. [Functional Programming] Read and Transform Values from a State ADT’s State (get)

    Many times we need to access and transform state, either in part or in full, to be used when calcula ...

  2. [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 ...

  3. [Functional Programming Monad] Combine Stateful Computations Using Composition

    We explore a means to represent the combination of our stateful computations using familiar composit ...

  4. [Functional Programming Monad] Modify The State Of A State Monad

    Using put to update our state for a given state transaction can make it difficult to modify a given ...

  5. [Functional Programming Monad] Map And Evaluate State With A Stateful Monad

    We explore our first stateful transaction, by devising a means to echo our state value into the resu ...

  6. [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 ...

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

  8. [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 ...

  9. [Functional Programming] Rewrite a reducer with functional state ADT

    For example we have a feature reducer like this: // selectCard :: String -> Action String export ...

随机推荐

  1. foj Problem 2282 Wand

     Problem 2282 Wand Accept: 432    Submit: 1537Time Limit: 1000 mSec    Memory Limit : 262144 KB Prob ...

  2. 百度之星初赛(A)——T2

    数据分割 小w来到百度之星的赛场上,准备开始实现一个程序自动分析系统. 这个程序接受一些形如x_i = x_jx​i​​=x​j​​ 或 x_i \neq x_jx​i​​≠x​j​​ 的相等/不等约 ...

  3. 【CF1020E】Sergey's problem(构造)

    题意: 思路:这是一道论文题 https://link.springer.com/content/pdf/10.1007/BFb0066192.pdf From http://www.cnblogs. ...

  4. DataTable转换为实体集合

    using System; using System.Collections; using System.Collections.Generic; using System.Data; using S ...

  5. linux c/c++ 代码使用 doxygen 自动生成文档

    www.doxygen.org 的使用非常方便,下面分成2步介绍一下 1. 注释风格,需要在c/c++代码中按照下面的风格添加注释,基本上还是很顺手的 C++的注释风格 主要使用下面这种样式:即在注释 ...

  6. 华为上机测试题(水仙花数升级版-java)

    PS:这题满分100,没有做对,大家帮忙看看问题在哪 /* * 题目:水仙花数升级版  * 描述: 水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身.(例如:1 ...

  7. 11.OpenStack 安装监控和业务流程服务

    安装业务流程模块 安装和配置业务流程 创建数据库 mysql -uroot -ptoyo123 CREATE DATABASE heat; GRANT ALL PRIVILEGES ON heat.* ...

  8. poj 1375(解析几何)

    Intervals Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 4292   Accepted: 1288 Descrip ...

  9. 写给小白看的 JavaScript 异步

    某天突然写了个方法要从后台调用数据,显示在前台页面,但是输出结果总是空 undefined,得不到数据.多方找资料才发现,原来是入了 JS 异步的 “坑”. 我们常常听到单线程.多线程.同步.异步这些 ...

  10. Doki Doki Literature Club

    Doki Doki Literature Club! is a visual novel developed by Team Salvato. The protagonist is invited b ...