【问题标题】:Ramda: Confused about pipeRamda:对管道感到困惑
【发布时间】:2019-06-05 17:15:12
【问题描述】:

我正在学习 JS 中的函数式编程,我正在使用 Ramda 进行学习。

我正在尝试制作一个接受参数并返回列表的函数。代码如下:

const list = R.unapply(R.identity);

list(1, 2, 3); // => [1, 2, 3]

现在我尝试使用pipe

const otherList = R.pipe(R.identity, R.unapply);

otherList(1,2,3);
// => function(){return t(Array.prototype.slice.call(arguments,0))}

返回一个奇怪的函数。

这个:

const otherList = R.pipe(R.identity, R.unapply);

otherList(R.identity)(1,2,3); // => [1, 2, 3]

出于某种原因工作。

我知道这可能是一个新手问题,但是如果 f 是 unapply 而 g 是 identity,你将如何用 pipe 构造 f(g(x))?

【问题讨论】:

  • 注意拼写是'Ramda',而不是'Rambda'。我已经为你编辑了。

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


【解决方案1】:

阅读R.unapplydocs。它是一个获取函数并返回函数的函数,它可以接受多个参数,将其收集到单个数组中,并将其作为包装函数的参数传递。

所以在第一种情况下,它将R.identity转换为一个可以接收多个参数并返回一个数组的函数。

在第二种情况下,R.unapply 得到R.identity 的结果 - 单个值,而不是函数。如果将R.identity作为参数传递给管道,R.unapply会得到一个函数并返回一个函数,和第一种情况类似。

要使R.unapplyR.pipe 一起工作,您需要将R.pipe 传递给R.unapply

const fn = R.unapply(R.pipe(
  R.identity
))

const result = fn(1, 2, 3)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

【讨论】:

  • unapply(pipe(identity)))unapply(identity)不一样吗?
  • @customcommander 可以,因为前者是unapply(x => identity(x))),可以eta降为unapply(identity))
【解决方案2】:

您可以使用unapply 将通常将其参数作为数组接收的函数转换为可以接收任意数量的位置参数的函数:

sum([1, 2, 3]); //=> 6
unapply(sum)(1, 2, 3) //=> 6

除其他外,这允许您映射任意数量的位置参数:

unapply(map(inc))(1, 2) //=> [2, 3]
unapply(map(inc))(1, 2, 3) //=> [2, 3, 4]
unapply(map(inc))(1, 2, 3, 4) //=> [2, 3, 4, 5]

identity 将始终返回其第一个参数。所以unapply(identity)(1,2)identity([1,2]) 是一样的。

如果您的最终目标是创建一个返回其参数列表的函数,我认为您首先不需要pipeunapply(identity) 已经在这样做了。

但是,如果您需要确保管道以列表的形式获取其参数,那么您只需将 pipe 包装为 unapply

const sumplusplus = unapply(pipe(sum, inc, inc));
sumplusplus(1, 2, 3); //=> 8

【讨论】:

    【解决方案3】:

    看来您确实在错误地考虑pipe

    当您使用unapply(identity) 时,您将函数 identity 传递给unapply

    但是当您尝试pipe(identity, unapply) 时,您会返回一个函数,该函数将调用identity结果传递给unapply

    这主要是巧合:pipe(identity, unapply)(identity)。把它想象成(...args) => unapply(identity(identity))(...args)。由于identity(identity) 只是identity,这就变成了(...args) => unapply(identity)(...args),可以简化为unapply(identity)。由于identity 的性质,这仅意味着重要的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 2012-07-22
      • 2013-05-13
      • 2020-04-16
      • 2023-03-08
      • 2019-08-04
      相关资源
      最近更新 更多