DEV Community

Discussion on: Currying in JavaScript

Collapse
 
jwp profile image
John Peters

Thanks for excellent simple explanation. However I must admit I see no valid reason for this pattern. It hides outcomes based on parameter counts, but later remembers prior values? It's like a dynamic function with pre determined state. What would the test pattern look like?

Collapse
 
jesuscovam profile image
jesuscovam

I think the same, but It could be useful for when a param must be computed from other functions, that you might already wrote outside the currying, sor I just my use like this currying(1)(resultOf(2))(3). That's my take in my head.

Collapse
 
jwp profile image
John Peters • Edited

Nice, this makes for placeholder to inject the results of functions.

However, we are also able to do this:

someFunction(1, get2ndParm(), 3);  Which is shorter.

Also, wouldn't currying break the pure function pattern?

Thread Thread
 
macsikora profile image
Pragmatic Maciej

Currying is not pattern. It is function property. In all FP languages functions are like that, so they are curried.

If you have function f: a ->b->c then by applying only a we have function g: b->c.

In JS as it's not FP language we need to make currying manually by using closures and returning function from function. It doesn't violate any purity as it is exactly FP concept.

Thread Thread
 
jwp profile image
John Peters

But has no value as far as I can tell.

Thread Thread
 
macsikora profile image
Pragmatic Maciej

If it would not have value it would not exists. It has huge value. But this answer would be worth a whole post about that ;)

Thread Thread
 
jesuscovam profile image
jesuscovam

maybe the second function would need a valued computed from the first function, so it could be use as a pipeline of computed values that are reusable and can be rearranged as legos

Collapse
 
pentacular profile image
pentacular

It's a way to make function interfaces uniform, so that a function becomes a transform from one input value to one output value.

Collapse
 
jwp profile image
John Peters

Code example please?

Thread Thread
 
pentacular profile image
pentacular
const add = a => b => a + b;
const eq = a => b => a === b;

eq(5)(add(2)(3));
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jwp profile image
John Peters

Just wondering how is that better than this?

const add(a,b)=>a+b;
add(2,3);

The decomposition of earlier example reveals a simpler understanding until one understands compositional parameter injection.

Thread Thread
 
pentacular profile image
pentacular

It's better if you want to use functions which have a uniform interface of transforming a single input value to a single output value.

Consider using map like so

[1, 2, 3].map(add(3))

Using the binary form of add you would need to introduce an ad hoc function to rectify the interface

[1, 2, 3.map(v => add(3, v))

The one to one mapping style generally makes composition simpler.

So, the question is, do you want to do that kind of stuff?

Collapse
 
wulymammoth profile image
David • Edited

This is a fair thought and/or assumption. I think the OP’s post is illuminating more so how it is done rather than how or why it could be useful or valuable. It would confuse the unacquainted if presented in a code based with those unfamiliar with the functional paradigm, too.

However, the value that I see in currying and partial application is composition — yeah... instead of writing an addTwo, addThree, addFour, addFive. It can simply be composed of a curried function. We use composition all the time by trying to perform code-reuse. Currying and partial application is just another tool or enabler and very standard in more purely functional languages — as we begin to think how we can make something with a sum of parts rather than building that something from scratch over and over again. If you’ve ever used underscore or the lodash libraries, Lodash declares its parameters in a very particular order to support this whereas underscore, unfortunately, does not. I’m on my phone so I cannot show the adder examples with code snippets but they can easily be found online.

Testing is simple — similarly to any unit test where we test what the expected behavior should be and they are: with no arguments supplied, some arguments supplied, and all arguments supplied and assert those outcomes

Collapse
 
jwp profile image
John Peters • Edited

See my better example below to point out how the 1 is hidden and no debugging will help determine where it came from.

Thread Thread
 
wulymammoth profile image
David • Edited

I'm not sure that I follow your example... if you've a function that reads sum, you expect it to produce a "sum". Right?

State is only relevant if it's mutable. If you supply an object with mutable state to a partially applied function, we're in for a debugging nightmare. I would even go so far as to say it's one of the reasons functional ideas have lackluster adoption in JS, unless we're dealing with scalar values or objects with immutable state.

Let's say that we have a function that helps us compute the size of a park plus some "buffer" that is only supplied at the time of construction, but we don't yet know before hand. We want to maintain a very specific interface: courts are supplied somewhere early in the process, but we expose to the builder only one parameter -- the buffer. They need not worry about courts and sizes, it is done somewhere earlier and up the chain.

function parkSize(courts) {
  return function(buffer) {
    return sum(courts) + buffer;
  }
}
Enter fullscreen mode Exit fullscreen mode

My example isn't very hard to test is it? The set-up involves two steps:

  1. supply court objects
  2. supply a buffer
  3. make an assertion

With the contrived example I have. I can "compose" a new function that exposes a "limited" and easy to understand interface for someone that needs to determine "recreational areas":

var courts = [...];
var parkArea = parkSize(courts); 
var buffer = 100; 
function recreationalSpace(buffer, privateSpace) {
  return sum(parkArea(buffer)) - privateSpace;
}
Enter fullscreen mode Exit fullscreen mode

This is no different than you using a library that's pre-configured -- you don't need to know all the default values before using it; one can infer based on the interface that's exposed. Otherwise, we could push for writing procedural imperative code that's all in a single file. How testable would that be?

Currying and partial application allow the designer/developer to control when arguments are supplied, otherwise you could end up having an outsized parameter list which forces the consumer of the function to know about the entire world at point of conception (runtime). The consumer of the function need not know about everything that was configured/supplied before it. Just like you don't need to know about all the internals of the library before you can use it. The only thing that should be implicit is the name of your function and what it's trying to convey... in the context of OOP, we this idea captured as well, called "encapsulation" -- prevent direct access to data except through a predetermined interface (methods). We don't want abstraction leaks and data access from everywhere. The consumer should need not know about the implementation details.

Every function that I've declared should be tested, so that if something is odd (like a bug), I know immediately where to look and what assumptions were made. It's really no different from us using a library that's hopefully well tested. We build tests upon a combination or composition of our own assumptions about what a library provides for us. In fact some of the libraries people use in JavaScript have functions that are exposed that are partially applied. You never need to dig into them unless seemingly unexpected behavior is exhibited after checking our own code...

Thread Thread
 
jwp profile image
John Peters • Edited

Thanks David I did some debugging today to figure this out.

 function sum(a) {
      return function (b, c) {
        return a + b + c;
      };
    }

    let mysum = sum(1);
    debugger;
    let mysum2 = mysum(2, 3);
    debugger;
Enter fullscreen mode Exit fullscreen mode

The results were:

As we can see, if a debugger wanted to know the value of mysum, in the console, they would only see it's a function as shown on far right side.

There's zero indication that this function when executed the 2nd time, has a preset value of 1 in it.

Now assume that mysum was set on entry to a module, but mysum2 was set much later. The developer is now wondering how mysum2 = 6...

mysum and mysum2 give no answers, but creating a de-composed form as shown in mysum3 kind-of, sort-of does help the debugger to understand.

This is what I was struggling with and why I mentioned an implicit state..

mysum is not a value, it's a function pointer! No values are returned until the 2nd and 3rd parameters are passed in. So this shows us that returning multiple functions forces a bit of thinking differently, as was said earlier it's composition of functions. Expressed in this syntax most clearly

let mysum3 = sum(1)(2,3);
Enter fullscreen mode Exit fullscreen mode

Indeed anonymous functions at that! I've seen this syntax before; but until now, didn't fully understand it.

Thanks!

Thread Thread
 
wulymammoth profile image
David • Edited

Ah! I love that your curiosity made you do a deeper dive! I went through something similar in other languages and honestly have never done currying or partial application in JS, although I've wanted to when I was spending most of my time in it.

Implicit state is always there, when you're working with a function that has had some arguments partially applied "earlier on". Does it make debugging more difficult? Yeah, it's not as easy as just shoving a break-point and inspecting current state. In languages, like Haskell, the lazy-evaluation becomes a challenge but yields performance gains. I work in Elixir which has nice facilities for this type of introspection, because it allows one to perform eager or lazy evaluation (Enum vs Stream) with the same functions in both modules

But I guess you're right, though -- that this idea (currying and partial application) isn't that useful in JS because it isn't the default paradigm that most of us are operating in. If employed, it would be analogous to using regexes everywhere and having to constantly explain them to everyone else. I very much like the ideas behind "functional reactive programming" ala RxJS where everything is a stream enabling some really really neat things one can do, but it is tough to get organizational buy-in when outside of some skunk-works team or small shop. But it is a powerful tool to maximize code reuse and a composition enabler in other languages and paradigms though