[Javascript Crocks] Apply a function in a Maybe context to Maybe inputs (curry & ap & liftA2)

Functions are first class in JavaScript. This means we can treat a function like any other data. This also means we can end up with a function as the wrapped value in a Maybe. The Maybe type gives us the ability to apply that wrapped function to other wrapped values, keeping both the value and the function in the safe confines of a Maybe.

 

The whole point is when we have params as safe params:

const safeNum1 = safe(isNumber, 1);
const safeNum2 = safe(isNumber, 2);

The function we need to opreate the params is not in a Maybe context:

const add = a => b => a + b;

Now we cannot just call 'add' function to add two Just(n) value together:

add(safeNum1, safeNum2) // doesn't work

Lucky we can also wrap function into Maybe context:

const safeAdd = Maybe.of(add);

 

We can use 'ap' function to apply context for a function

复制代码
const crocks = require('crocks')
const { ap, safe, isNumber, Maybe } = crocks;

const safeNum1 = safe(isNumber, 1);
const safeNum2 = safe(isNumber, 2);

const add = a => b => a + b;

const res = Maybe.of(add)
    .ap(safeNum1)
    .ap(safeNum2);

console.log(res) // Just 3
复制代码

 

We can improve the code by using 'curry' instead of 

const add = a => b => a + b;

to:

const crocks = require('crocks')
const { curry } = crocks;
const add = curry((a, b) => a + b);

 

 

We can also using a helper method 'liftA2' to replace calling 'ap' multiy times:

const res = Maybe.of(add)
    .ap(safeNum1)
    .ap(safeNum2);

to:

复制代码
const crocks = require('crocks')
const { ap, safe, isNumber, Maybe, curry, liftA2 } = crocks;

const safeNum1 = safe(isNumber, 1);
const safeNum2 = safe(isNumber, 2);

const add = curry((a, b) => a + b);

const addTwoSafeNums = liftA2(add);
const res = addTwoSafeNums(safeNum1, safeNum2);

console.log(res) // Just 3
复制代码

 

posted @   Zhentiw  阅读(239)  评论(0编辑  收藏  举报
编辑推荐:
· 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工具
历史上的今天:
2017-05-14 [Recompose] Add Local State with Redux-like Reducers using Recompose
2017-05-14 [Recompose] Add Local State to a Functional Stateless Component using Recompose
2016-05-14 [Javascript] Advanced Console Log Arguments
2016-05-14 [Javascript] Log Levels and Semantic Methods
点击右上角即可分享
微信分享提示