0

I'm learning about currying and I decided to try to make a curried minimum function called getMin.

To my understanding, this means that I should be able to call getMinimum(5)(2)(6) and have it return 2.

I tried to implement this with a simple closure and I came up with something that returns numbers instead of functions. Here's my code:

function getMin(val){
    var min = val
    function calc(num){
        if(num<min){
            // set new minimum
            min = num
            return num
        }
        else {
            return min
        }
    }
    return calc
}


var x = getMin(5) // => 5
console.log(x(6))
console.log(x(4))
console.log(x(8))
console.log(x(2))

This logs:

5
4
4
2

This doesn't meet the requirements of currying.

So as I consider how I might change this function so that it returns a function, I run into a problem. Every time the curried function is called with a number argument, it should return the minimum (a number), but if I am understanding this correctly, it should also return a function (so that it can be called once again with another number). How does this work?

1
  • 1
    you never log x which is the return of getMin(5). That's the function Commented Jan 11, 2019 at 9:04

2 Answers 2

3

You need to implement a toString function, which returns the result, if a primitive value is required, otherwise a function.

function getMinimum(m) {
    function min(v) {
        m = Math.min(m, v);
        return min;
    }
    min.toString = _ => m;
    return min;
}


console.log(getMinimum(5)(2)(6));
console.log(getMinimum(3)(2)(1)(-1000));

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

1 Comment

@MoritzRoessler, that does not work here, because this implementation of console.log needs a string, whereas valueOf with a number yields the function itself.
3

No, you are misunderstanding currying. It doesn't mean that your function should take an arbitrary amount of arguments (see here on how to do that while allowing multiple chained calls), but only that it should takes only a single argument value at a time. Your getMin function already is curried, it has the signature number -> (number -> number) (taking two numbers, returning one). If it wasn't curried you'd have to call it as getMin(5, 4).

2 Comments

If getMin is already curried, shouldn't I be able to call getMin(5)(4)(6) and get 4? When I try this I get getMin(...)(...) is not a function
I see your point; you're not necessarily saying the function is valid, just that it's curried.

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.