[Functional Programming Monad] Apply Stateful Computations To Functions (.ap, .liftA2)
When building our stateful computations, there will come a time when we’ll need to combine two or more state transactions at the same time to come up with a new result. Usually this occurs when want to use plain ol’ JavaScript functions with two or more a arguments as part of our stateful computations.
We first look at how this can be accomplished by using chain
and closure to get access to both functions. Then we will explore how we can leverage the of
construction helper and the ap
State
instance method to clean this type of interaction up a bit. We then conclude with an even cleaner approach that takes full advantage of a crocks
helper function named liftA2
.
For example, we have a function:
const namefiy = firstName => lastName => `${lastName}, ${firstName}`;
It should receive two params to return a string.
one way is using .ap(), it takes the same input, run with the given functions and return its value, then combine those:
var _getFullName = State.of(namefiy) .ap(getFirstName) .ap(getLastName)
Or we can use .liftA2, it lift the function into State automaticlly:
var getFullName = liftA2( namefiy, getFirstName, getLastName )
----
const { liftA2, composeK, Unit, curry, objOf, compose, State, mapProps, prop, option } = require("crocks"); const { put, get, modify } = State; const namefiy = firstName => lastName => `${lastName}, ${firstName}`; const getWord = number => name => name.split(' ')[number]; const getFirstName = get(getWord(0)); const getLastName = get(getWord(1)); var _getFullName = State.of(namefiy) .ap(getFirstName) .ap(getLastName) var getFullName = liftA2( namefiy, getFirstName, getLastName ) console.log( getFullName .evalWith("John Green") )
【推荐】国内首个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-31 [React] Refactor a Stateful List Component to a Functional Component with React PowerPlug
2018-01-31 [MST] Use Volatile State and Lifecycle Methods to Manage Private State
2017-01-31 [React] Test friendly approach
2017-01-31 [React] Modify file structure
2017-01-31 [Javascript] Format console.log with CSS and String Template Tags
2017-01-31 [Angular] ChangeDetection -- onPush
2016-01-31 [Javascript] Redirect the browser using JavaScript