gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:00:12 24 4
gpt4 key购买 nike

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

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

我使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com