javascript - 如何使用 Ramda.js 合并 2 个组合

标签 javascript functional-programming ramda.js

我有一个要转换的字符串:

“正确替换我” => “正确替换我”

我使用 Ramda.js 的代码:

const _ = R; //converting Ramda.js to use _

const replaceTail = _.compose(_.replace(/-/g, ' '), _.tail);
const upperHead = _.compose(_.toUpper ,_.head);

const replaceMe = (str) => _.concat(upperHead(str) , replaceTail(str));

replaceMe("replace-me-correctly"); // "Replace me correctly"

我想知道的是,是否有一种更简洁、更有效的方法将 replaceTailupperHead 组合在一起,这样我只遍历字符串一次?

JSBin example

最佳答案

不确定只遍历字符串一次。听起来很难。不过,我会提供一些不同的方法来获得乐趣和洞察力。

函数的 monoid 实例将通过使用给定参数运行它们并连接它们的结果来连接每个函数(它们必须全部返回相同的类型才能正确组合)。 replaceMe 正是这样做的,因此我们可以改用 mconcat

const { compose, head, tail, replace, toUpper } = require('ramda')
const { mconcat } = require('pointfree-fantasy')

// fun with monoids
const replaceTail = compose(replace(/-/g, ' '), tail)
const upperHead = compose(toUpper, head)
const replaceMe = mconcat([upperHead, replaceTail])

replaceMe("replace-me-correctly")
//=> "Replace me correctly"

这是一种组合函数的有趣方式。我不确定为什么要求在 replace 之前捕获 tail。似乎 replace 函数可以更新为仅通过正则表达式替换起始字符之后的任何 -。如果是这种情况,我们可以内联 replace

还有一件事。 Profunctor 的 dimap 函数实例非常简洁,镜头也是如此。一起使用它们,我们可以将字符串转换为数组,然后 toUpper 只是第 0 个索引。

const { curry, compose, split, join, head, replace, toUpper } = require('ramda')
const { mconcat } = require('pointfree-fantasy')
const { makeLenses, over } = require('lenses')
const L = makeLenses([])

// fun with dimap
const dimap = curry((f, g, h) => compose(f,h,g))
const asChars = dimap(join(''), split(''))
const replaceMe = compose(replace(/-/g, ' '), asChars(over(L.num(0), toUpper)))

replaceMe("replace-me-correctly")
//=> "Replace me correctly"

关于javascript - 如何使用 Ramda.js 合并 2 个组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948482/

相关文章:

javascript - 比较 ramda.js 中的部分对象

javascript - 如何从代码隐藏中删除 Html <li> 元素符号?

javascript - React js 和 flux 用户存储安全

javascript - 获取 HTML Body 中的 Javascript 变量

functional-programming - 函数式编程是声明式编程的一种吗?

javascript - Rethinkdb 将对象数组转换为单个对象

javascript - 在 JS 中向突出显示的文本添加标签不起作用

haskell - "error"函数的存在如何影响 Haskell 的纯度?

javascript - lambda 斯 : locating items with an inner array that satisfies a spec

javascript - 如果对象包含带有空数组的键,如何删除该对象?