【问题标题】:Confused about javascript function returning multiple functions with many fat arrow对 javascript 函数返回多个带有许多粗箭头的函数感到困惑
【发布时间】:2019-08-31 08:47:51
【问题描述】:

我的 cs 作业有问题。 我需要访问函数的 x 值,但我的代码返回的是一个空函数而不是值

我已经用谷歌搜索了所有的柯里化和闭包,但它们都不够先进,无法帮助我解决问题

const pair = (x, y) => f => f(x, y);  // Do not edit this function
const head = p => //Answer here                

console.log(head(pair(1,2)))          // Do not edit this

当我尝试所有组合时,我的控制台不断返回functions

function(a,b){return a;}

【问题讨论】:

    标签: javascript function ecmascript-6 closures currying


    【解决方案1】:

    您可以像这样更改head 函数:

    const pair = (x, y) => f => f(x, y); 
    const head = f => f(a => a)
    
    console.log(head(pair(1,2)))

    【讨论】:

    • @Peter 在这里,pairhead 之前执行。可以加console.log()查看。
    • @Peter 现在看到了您对问题的编辑。更新head
    • @Peter 我没听懂你。 “作为参数传入函数”在哪里?
    • @adiga 看了超长的f(a=> a) 部分我没看懂
    • a => a 是一个箭头函数,就像(x, y) => f。如果太混乱,你可以像(a, b) => a这样写
    【解决方案2】:

    我的控制台一直向我返回这个而不是

    function(a,b){return a;}

    让我们更容易阅读。在 ES5 中,您的代码如下所示:

    var pair = function(x, y) {
      return function(f) {
        return f(x, y);
      }
    };
    
    var head = function(p) {
      return function(a, b) {
        return a;
      }
    };
    

    您需要将head返回的函数传递给pair(1, 2)返回的函数。所以你需要交换你调用函数的顺序:

    console.log(pair(1, 2)(head()));
    

    【讨论】:

    • 然后交换每个函数中的逻辑。
    【解决方案3】:

    不确定我是否正确理解了您的问题,但我猜您正在尝试这样做

    const pair = (x, y) => f => f(x, y); 
    const head = (x, y) => x;
    
    console.log((pair(1,2)(head)))

    如果不是,那么上面的这个是正确的

    const pair = (x, y) => f => f(x, y); 
    const head = f => f(a => a);
    
    console.log(head(pair(1,2)))

    【讨论】:

    • 这增加了什么?上面的答案中已经提到了这两个
    • 第一个和上面的不一样,但是第二个是的。我无法在这里评论他们提到的这一点。
    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 2018-05-04
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多