简体   繁体   English

对javascript函数返回带有多个粗箭头的多个函数感到困惑

[英]Confused about javascript function returning multiple functions with many fat arrow

I have problem with my cs homework. 我的CS作业有问题。 I need to access the x value of the function, but my codes is returning me an empty function instead of with the values 我需要访问该函数的x值,但是我的代码向我返回了一个空函数,而不是值

I have googled all the currying and closures, but none of them are advanced enough to help me solve my problem 我已经用Google搜索了所有的currying和closes,但是它们都不先进,无法帮助我解决问题

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

my console keeps returning me functions instead when I try all the combinations 当我尝试所有组合时,控制台会不断返回我的functions

function(a,b){return a;}

You could change head function like this: 您可以这样更改head功能:

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

my console keeps returning me this instead 我的控制台不断向我返回

function(a,b){return a;}

Let's make this easier to read. 让我们更容易阅读。 In ES5, your code looks like this: 在ES5中,您的代码如下所示:

var pair = function(x, y) {
  return function(f) {
    return f(x, y);
  }
};

var head = function(p) {
  return function(a, b) {
    return a;
  }
};

You need to pass the function returned from head to the function returned by pair(1, 2) . 您需要将从head返回的函数传递给pair(1, 2)返回的函数。 So you need to swap which order you're calling the functions in: 因此,您需要交换调用函数的顺序:

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

Not sure if I understand your question correctly or not but I guess you are trying to do this 不知道我是否正确理解了您的问题,但我想您正在尝试这样做

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

if not then this one from above is correct 如果不是,那么上面的这个是正确的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM