在 Ramda 中组合具有更高属性的函数

Composing function with higher arity in Ramda

我很想学习js的函数式编程,但是我遇到了困难。我觉得我一直在做这样的事情,感觉一点都不对:

export const getParamFromUrl = R.curry((name, url) => R.compose(
    R.match(new RegExp(`[?&]${name}=([^&]*)`))
)(url));

我觉得我不应该立即调用 compose。那么用两个元数进行函数组合的正确方法是什么?

编辑:为清楚起见,这是实际的函数(我知道这不是获取查询字符串的最佳方式)

/* util.toMaybe takes a function and a value and returns Nothing()
   if the function returns true and Just(value) if it returns false.
   I think this is the HM:
   util.toMaybe :: (a -> Boolean) -> a -> Maybe a
*/
export const getParamFromUrl = R.curry((name, url) => R.compose(
    R.chain(util.toMaybe(R.isEmpty)),
    R.map(R.nth(1)),
    util.toMaybe(R.isEmpty),
    R.match(new RegExp(`[?&]${name}=([^&]*)`))
)(url));

有了接受的答案,这将变成:

export const getParamFromUrl = R.curry(R.compose(
    R.chain(util.toMaybe(R.isEmpty)),
    R.map(R.nth(1)),
    util.toMaybe(R.isEmpty),
    (name, url) => R.match(new RegExp(`[?&]${name}=([^&]*)`), url)
));

不太清楚您要对 compose 调用做什么。没有它,该功能同样可以正常工作,并且更加清晰。

const getParamFromUrl = R.curry((name, url) => 
    R.match(new RegExp(`[?&]${name}=([^&]*)`), url));

如果您打算在组合中添加另一个功能,那么您可以这样做:

const getParamFromUrl = R.curry(R.compose(
    nth(1),
    (name, url) => R.match(new RegExp(`[?&]${name}=([^&]*)`), url)
));

注意for technical reasonscompose的结果不是自动柯里化的,所以你需要自己做。

您可以在 Ramda REPL.

上看到实际效果