【问题标题】:Functional Programming with Ramda: Can you curry a function that takes unlimited number of arguments使用 Ramda 进行函数式编程:你能 curry 一个接受无限数量参数的函数吗
【发布时间】:2016-07-17 02:36:12
【问题描述】:

假设我有 3 个数组

var first = [0, 1, 2, 3];
var second = [0, 1, 2, 3];
var third = [0, 1, 2, 3];

我想创建一个 curried 函数,在其中设置第一个参数,指示我想在作为参数传递的数组中添加哪个单元格......理想情况下,我希望该函数能够获取无限数量的数组。 ...

例如: mycurriedfunction(1) 表示我想访问我传入的数组的单元格 1 处的值并将它们相加。

因此做:

mycurriedfunction(1)(first) 将返回 1

mycurriedfunction(1)(first)(second) 将返回 2

mycurriedfunction(2)(first)(second)(third) 将返回 6

这可能吗?

如果不是,那么有哪些替代方案可以实现相似甚至相同的结果?

【问题讨论】:

  • 那么你需要可执行的数字类型吗?你可以试试这个:jsbin.com/xupaha/edit?js,console
  • 这很简单:myFn(2, [first, second, third])。但是你的 API 是不可能的。 @iofjuupasli 的模拟可能是你能做的最好的,但不是特别接近。

标签: functional-programming currying ramda.js


【解决方案1】:

不,一个值不可能既是数字又是函数。

你应该让你的函数取而代之的是一个列表,或者被表述为一个 reducer。

【讨论】:

    【解决方案2】:

    正如其他人所提到的,您描述的函数无法知道是返回下一个要调用的函数还是返回最终值。

    如果你真的想实现类似的东西,接受无限数量的数组,你可以稍微调整一下,将累积的值存储为返回函数的属性。

    function sumIdx(idx) {
      function f(value) {
        function g(arr) {
          return f(value + arr[idx]);
        }
        g.value = value;
        return g;
      }
      return f(0);
    }
    

    这可以像您的示例一样使用,不同之处在于您需要在完成后从value 属性中提取结果。

    const first  = [0, 1, 2];
    const second = [3, 4, 5];
    const third  = [6, 7, 8];
    
    sumIdx(2)(first)(second)(third).value // 15
    

    虽然可能,但我可能不建议使用这种方法。也许使用单独的数据类型会更好地表示这种行为(或者按照 Scott Sauyet 对myFn(2, [first, second, third]) 的建议更改您的 API)。

    class SumIdx {
      constructor(idx, value) {
        this.idx = idx;
        this.value = value;
      }
      next(arr) {
        return new SumIdx(this.idx, this.value + arr[this.idx]);
      }
    }
    
    const sumIdx = idx => new SumIdx(idx, 0);
    

    这里的区别是需要调用next方法而不是直接调用结果。

    sumIdx(2).next(first).next(second).next(third).value // 15
    

    【讨论】:

    • 你刚刚给信任你的人开了毒药
    猜你喜欢
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2011-03-05
    • 1970-01-01
    • 2012-02-20
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多