【问题标题】:Composing function with higher arity in RamdaRamda中具有更高arity的组合函数
【发布时间】:2017-04-14 04:27:09
【问题描述】:

我急切地想学习 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)
));

【问题讨论】:

  • 也许我没有得到功能方面的东西。你需要马上咖喱吗?像(name, url) => url.match(new RegExp())[1] 这样的常规函数​​有什么问题,您以后可以随时包装/咖喱该函数,对吧?
  • 这也是一种非常不可靠的URL参数解析方式

标签: javascript functional-programming function-composition ramda.js


【解决方案1】:

目前还不清楚您对 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)
));

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

您可以在 Ramda REPL 上看到这一点。

【讨论】:

  • 非常感谢,编写更高元的函数非常有意义。我觉得这个想法正是我一直在寻找的,但我自己却无法解决。我已经编辑了我的问题,试图阐明我为什么首先使用构图。
猜你喜欢
  • 2015-12-15
  • 1970-01-01
  • 2018-03-13
  • 2019-04-12
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多