[Functional Programming Monad] Refactor Stateful Code To Use A State Monad
When we start to accumulate functions that all work on a given datatype, we end up creating a bunch of boilerplate code in almost every function to handle the changes we need to make to our records’ values. This can lead to not only undesirable boilerplate present in all of our functions, but also can cause us to have to create variables just to manage our stateful changes.
We’ll take a look at a couple patterns that can act as early warning signs that will eventually cause us to not have a good time. Once we know what the smell is, we’ll look at how moving our computations into State
can clean up all of our state management code by making it the responsibility of State
. This allows our functions to only describe how state should change over time versus us having to change it ourselves.
Imaging we have a user object, if we want to udpate firstName prop, we have to update fullName as well.
const user = { firstName: 'John', lastName: 'Green', fullName: 'John Green' }
Code like this:
const _buildFulName = user => { const {firstName, lastName} = user; const fullName = joinName(firstName, lastName) return _updateFullName(fullName, user) } const _updateFirstName = curry( firstName => compose( _buildFulName, assign({firstName}) ) ) const _updateFullName = curry( fullName => assign({fullName}) )
We want to use a more flexiable way to do it:
const getState = (key) => get(prop(key)) const getFirstName = () => getState('firstName').map(option('')); const getLastName = () => getState('lastName').map(option('')); const joinName = firstName => lastName => `${firstName}, ${lastName}` const buildFullName = () => liftA2( joinName, getFirstName(), getLastName() ).chain(updateFullName) const updateFirstName = firstName => modify( assign({firstName}) ).chain(buildFullName); const updateFullName = fullName => modify( assign({fullName}) )
【推荐】国内首个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