[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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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-01-23 [MST] Test mobx-state-tree Models by Recording Snapshots or Patches
2018-01-23 [MST] Attach Behavior to mobx-state-tree Models Using Actions
2018-01-23 [MST] Describe Your Application Domain Using mobx-state-tree(MST) Models
2018-01-23 [Angular] Configure an Angular App at Compile Time with the Angular CLI
2018-01-23 [Angular] Configure an Angular App at Runtime
2018-01-23 [Test] Easy automated testing in NodeJS with TestCafe
2017-01-23 [Compose] Isomorphisms and round trip data transformations