我正在尝试学习如何在 javascript 中使用应用仿函数,并遇到了 ap
方法。我正在尝试使用它来组合三个数组,如下所示:
const products = ['teeshirt', 'sweater']
const options = ['large', 'medium', 'small']
const colors = ['red', 'black']
所以根据 documentation我正在尝试这个:
const buildMerch = product => option => color =>`${product}-${option}-${color}`
const merchandise = R.ap([buildMerch], [products, options, colors])
但这给了我三个功能:
[function (option) {
return function (color) {
return product + '-' + option + '-' + color;
};
}, function (option) {
return function (color) {
return product + '-' + option + '-' + color;
};
}, function (option) {
return function (color) {
return product + '-' + option + '-' + color;
};
}]
...而不是我期望的数组的组合结果:
["teeshirt- large-red", "teeshirt- large-black", "teeshirt- medium-red", "teeshirt- medium-black", "teeshirt- small-red", "teeshirt- small-black", "sweater- large-red", "sweater- large-black", "sweater- medium-red", "sweater- medium-black", "sweater- small-red", "sweater- small-black"]
我做错了什么?我该如何解决这个问题?
这是一个有问题的 jsbin:https://jsbin.com/fohuriy/14/edit?js,console
最佳答案
根据文档,
ap
将函数列表应用于值列表。您的函数 buildMerch
具有以下“类型”:
buildMerch :: String -> String -> String -> String
最简单的 ap
是 map
:对于任何应用仿函数,我们得到:
pure f <*> a
======
map f a
对于数组,纯
是x => [x]
。所以,
R.ap([buildMerch], [foo, bar, baz])
======
R.map(buildMerch, [foo, bar, baz])
通过将 buildMerch
映射到参数列表,我们将其部分应用于相关数组。做你想做的表达是:
const merchandise = R.ap(R.ap(R.map(buildMerch, products), options), colors);
首先,我们将 buildMerch
映射到产品数组。这为我们提供了一个带有两个参数的函数数组:[String -> String -> String]
。然后,我们使用 R.ap
将其与 options::[String]
相结合,它将第一个数组中的每个函数与 options< 中的每个参数一起应用
数组。现在我们有了 [String -> String]
,最后我们用 colors
来 R.ap
来得到你想要的最终字符串数组.
关于javascript - 什么是我的应用仿函数不能与 Ramda 的 ap 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752031/