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?

David J.
  • 1,753
  • 13
  • 47
  • 96

2 Answers2

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • @MoritzRoessler, that does not work here, because this implementation of `console.log` needs a string, whereas `valueOf` with a number yields the function itself. – Nina Scholz Jan 11 '19 at 09:07
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).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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` – David J. Jan 11 '19 at 09:14
  • I see your point; you're not necessarily saying the function is valid, just that it's curried. – David J. Jan 11 '19 at 09:18