[Functional Programming 101] Crocks.js -- when to use map and when to use chain?
As a beginner of Crocks.js, it was a problem for we to figure out when to use .map() and when to use .chain().
Of course, using the docs help:
map: State s a ~> (a -> b) -> State s b
chain: State s a ~> (a -> State s b) -> State s b
The main difference is that, when using .map(fn), the param is a function.
For exmaple: addOne is just a plain function.
const addOne = x => x + 1;
When using .chian(sfn), the param is a State(fn)
For example: modify return a state() and inside state(), we apply function addOne.
const modifyOne = () => modify(mapProps({'moves', addOne}));
Now, we are going to write two example, one is using .map() another one is using .chain() to achieve the same result.
// We want to get final result as {moves: 4} const state = { moves: 1 }
.chain():
const { curry, compose, State, mapProps, prop, option } = require("crocks"); const { modify, get } = State; const getState = key => get(prop(key)); const addOne = x => x + 1; const modifyOne = () => over('moves', addOne); const over = (key, fn) => modify(mapProps({[key]: fn})) const state = { moves: 1 } const getMoves = () => getState('moves').map(option(0)) console.log( getMoves() .chain(modifyOne) .chain(modifyOne) .chain(modifyOne) .execWith(state) // {moves: 4} )
Notice that 'getMoves' and 'modifyOne' both return State(), so they have to use .chian().
.map():
const { curry, compose, State, mapProps, prop, option } = require("crocks"); const { modify, get } = State; const getState = key => get(prop(key)); const addOne = x => x + 1; const state = { moves: 1 } const getMoves = () => getState('moves').map(option(0)) console.log( getMoves() .map(addOne) .map(addOne) .map(addOne) .evalWith(state) // 4 )
Since 'addOne' is just a function, we can use .map() instead of .chian(). And more important, we have to use 'evalWith' to get result value, since we are not using 'modify' to change the state.
相关文章
- golang中的map并发读写问题: Golang 协程并发使用 Map 的正确姿势
- js 生成二维码 vue项目
- js map函数的用法
- 花上百万元用three.js开发的元宇宙空间,在线大型车展参考案例
- js事件循环、window.setTimeout 延迟执行详解编程语言
- JS map()方法:对数组的每个元素调用指定的回调函数
- 使用JS连接MySQL数据库:实现化繁为简(js连接mysql数据库)
- 使用Redis存储Map结构数据(redis存储map)
- Redis精准读取Map数据的窍门(redis获取map)
- Linux上的JS压缩工具(js压缩工具linux)
- 利用 JS 实现 Redis 的连接(js连接redis)
- 使用 JS 操作 Redis:实现强大数据存储.(js调用redis)
- MySQL中使用Map作为参数的实现方法(mysql中map做参数)
- 使用Redis存储Map结构数据(将map存到redis中)
- Oracle中Map结构的精妙运用(oracle中MAP结构)
- 在Redis中使用Map存储数据(redis里面加入map)
- 探索Redis中的Map之谜(redis里查map)
- js发个判断字符串是否为符合标准的函数
- JS页面自动加载函数(兼容多浏览器)
- 使用JS进行目录上传(相当于批量上传)
- js排序动画模拟-插入排序
- js怎么终止程序return不行换jfslk
- JS文本获得焦点清除文本文字的示例代码
- 倒记时60刷新网页的js代码