javascript - 什么是我的应用仿函数不能与 Ramda 的 ap 一起工作?

标签 javascript functional-programming ramda.js applicative

我正在尝试学习如何在 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

最简单的 apmap:对于任何应用仿函数,我们得到:

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],最后我们用 colorsR.ap 来得到你想要的最终字符串数组.

关于javascript - 什么是我的应用仿函数不能与 Ramda 的 ap 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752031/

相关文章:

javascript - AngularJS-ngOptions : How to order by Group Name and then by Label

javascript - 在触发一系列ajax请求时排队

Haskell - 将联合列表转换为列表元组

dictionary - clojure 101 将向量组合成 map

ramda.js - Ramda 相当于 underscore.js 'compact' 是什么?

javascript - 如何使用 JS 检测 iPhone 上粘贴的文本?

functional-programming - 函数式语言如何模拟副作用?

javascript - 你如何阅读 ramda 文档?

javascript - 如何使用数组项预加载 Ramda 柯里化(Currying)函数?

javascript - 单击并加载后的 Jquery 复制并粘贴部分 HTML