[Ramda] Eliminate Function Arguments (Point-Free Style) with Ramda's Converge

When doing comparisons inside of functions, you end of relying heavily on the argument passed into the function. Ramda's converge allows you to do comparisons in a Point-Free style allowing you more flexibility with composing and constructing functions. This lesson walks through refactoring a function to Point-Free style using Ramda's Converge.

 

For example we want to find the whether the first item of an array is the biggest number:

const shouldBeTrue = [6, 3, 4, 5, 2, 1]
const shouldBeFalse = [3, 4, 5, 2, 1]

const isFirstBiggest = (xs) => xs[0] == xs.sort((a, b) => b - a)[0]

console.log(isFirstBiggest(shouldBeTrue)) // true
console.log(isFirstBiggest(shouldBeFalse)) // false

In the code we can see this:

const isFirstBiggest = (xs) => xs[0] === xs.sort((a, b) => b - a)[0]

You can find that, param 'xs' appears both on the left and right side of euqals sign.

If match this partten, we actually can use 'converge' from  Ramda.

invoked, this new function is applied to some arguments, each branching function is applied to those same arguments. The results of each branching function are passed as arguments to the converging function to produce the return value.

For example:

复制代码
const shouldBeTrue = [6, 3, 4, 5, 2, 1]
const shouldBeFalse = [3, 4, 5, 2, 1]

import {
  converge, equals, head, sort, descend, identity, compose
}
from 'ramda'

const biggestNumberOfArray = compose(
  head,
  sort(descend(identity))
);
const isFirstBiggest = converge(
  equals, [
    head,
    biggestNumberOfArray
  ]
);

// xs =>
//     xs[0] == xs.sort((a, b) => b - a)[0]



console.log(isFirstBiggest(shouldBeTrue))
console.log(isFirstBiggest(shouldBeFalse))
复制代码

So in the code:

converge(
  equals, [
    head,
    biggestNumberOfArray
  ]
)

converge takes two params, first params is 'R.equals'. It tells what should do with the second param. Here is checking whether they are equal.

Second param is an array, take tow expersions.

R.head --> xs[0]
biggestNumberOfArray --> xs.sort((a,b) => b-a)[0]

 

More example:

var average = R.converge(R.divide, [R.sum, R.length])
average([1, 2, 3, 4, 5, 6, 7]) //=> 4

var strangeConcat = R.converge(R.concat, [R.toUpper, R.toLower])
strangeConcat("Yodel") //=> "YODELyodel"

 

posted @   Zhentiw  阅读(288)  评论(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工具
点击右上角即可分享
微信分享提示