Ramda 链使用 [英] Ramda chain usage

查看:45
本文介绍了Ramda 链使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档:

var duplicate = n => [n, n];
R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1]

第一个示例非常简单,它将重复()应用于数组中的每个元素并连接结果.但是我无法理解第二个示例.它究竟是如何在数组上映射 R.append + R.head 的?有人可以为第二个例子提供一步一步的解释吗?

The first example is very straight forward, it applies duplicate() to every element in the array and concatenates the result. But I am having trouble understanding the second example. How exactly is it mapping R.append + R.head over the array? Can someone please provide a step by step explanation for the second example ?

我熟悉 compose 和 currying.

I am familiar with compose and currying.

谢谢

推荐答案

第二个例子展示了 R.chain 如何使用数组以外的东西,比如函数(或任何实现 Fantasy土地 chain 规范).

The second example is showing how R.chain can be used things other than arrays, such as functions (or anything implementing the Fantasy Land chain spec).

如果您熟悉映射然后连接数组的概念,您可以将一个函数映射到另一个函数上作为普通的函数组合.连接部分需要进一步解释.

If the concept of mapping and then concatenating an array is familiar to you, you can think of mapping a function over another function as plain function composition. The concatenating part will require further explanation.

R.chain 声明其签名为:

Chain m => (a → m b) → m a → m b

对于数组,我们可以将 m[] 交换得到:

For arrays, we can swap the m with [] to get:

(a → [b]) → [a] → [b]

对于接收一些参数 r 的函数,它变成:

For functions that receive some argument r, it becomes:

(a → r → b) → (r → a) → (r → b)

因此,只有了解这些类型的可用知识,生成最终 r → b 函数的唯一方法是执行以下操作:

So with only the knowledge of those types available, the only way to produce the final r → b function is to do the following:

  • 将接收到的参数 r 传递给第二个函数以生成 a
  • 将新的 a 和原始的 r 应用到第一个函数以生成结果 b
  • Pass the received argument r to the second function to produce an a
  • Apply both the new a and the original r to the first function to produce the resulting b

或在代码中:

// specialised to functions
const chain = (firstFn, secondFn) =>
  x => firstFn(secondFn(x), x)

将示例中的函数交换,可以看到它变成了:

Swapping in the functions from the example, you can see it becomes:

x => R.append(R.head(x), x)

如果您熟悉 R.converge 那么这是有效的:

If you are familiar with R.converge then this is effectively:

R.converge(firstFn, [secondFn, R.identity])

这篇关于Ramda 链使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆