3

It may be a very strange question, but I need to be sure if it really exists or not. I've got the recruitment task for a PHP developer position with the following task:

Make a function to sum two numbers a and b but it must be called as sum(a)(b)

I've never seen anything like that and can't find anything about functions like the above. The recruiter says it's not a typo; I'm confused.

2
  • 1
    Not sure about PHP, but that would be easy enough in JavaScript. It would just mean that the sum function takes one argument and returns a function which itself takes on argument. Can PHP return functions like JavaScript can? Commented Jun 24, 2014 at 13:34
  • 2
    The correct answer is: "PHP is not Javascript". Commented Jun 24, 2014 at 13:42

1 Answer 1

10

This assignment expects you to understand partial application. Basically, your sum function should return a function that accepts one argument and takes the other one from the surrounding closure:

// Javascript
function sum(a) { return function(b) { return a + b  } }
sum(3)(4) // 7

You can do almost the same in php:

function sum($a) {
    return function($b) use($a) {
        return $a + $b;
    };
}

but since php doesn't allow two calls in a row, you'll need a temporary variable:

$add3 = sum(3);
print $add3(4); // 7

This

 sum(3)(4);

is not possible in php (as of 5.5) - parse error.

I'm pretty sure your interviewer actually means javascript, not php (note the lack of $'s in the assignment).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.