Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. ...
For further actions, you may consider blocking this person and/or reporting abuse
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?
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
See my better example below to point out how the 1 is hidden and no debugging will help determine where it came from.
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.
My example isn't very hard to test is it? The set-up involves two steps:
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":
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...
Thanks David I did some debugging today to figure this out.
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
Indeed anonymous functions at that! I've seen this syntax before; but until now, didn't fully understand it.
Thanks!
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
vsStream
) with the same functions in both modulesBut 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
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.
Nice, this makes for placeholder to inject the results of functions.
However, we are also able to do this:
Also, wouldn't currying break the pure function pattern?
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.
But has no value as far as I can tell.
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 ;)
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
It's a way to make function interfaces uniform, so that a function becomes a transform from one input value to one output value.
Code example please?
Just wondering how is that better than this?
The decomposition of earlier example reveals a simpler understanding until one understands compositional parameter injection.
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?
This is not partial application in its imperative meaning:
It is a curried function that returns a multi-argument one.
Partial application is a dynamic concept of imperative programming. Here is a possible approach:
How partial application have any imperative meaning? Partial application is just possibility of applying to function less arguments than function defines. If function is curried then partial application is just using this function property.
Note that real curry should return functions until all arguments are added. This is curry function I use in my code:
But also this function is modification of real concept of curry that return single argument functions only. Here you can use multiple arguments at once (which is much better).
You can test the curry function at: codepen.io/jcubic/pen/LxrOYP the code in demo use ES5.
Hey @Suprabha, thank you for this article. I just want to know in real-world why we need currying and where I should use currying. 🤔 As a developer, I would like to know the kind of problems you solve with currying.🤓🧐
Again Thank you...
I make heavy use of currying with functional pipelines.
Here's an example of comparing a function pipeline with method chaining from a recent tweet.
src
twitter.com/Reactivizer/status/127...
the filterNotStartsWith and replaceByRegex funcs are curried (they are funcs that return funcs)
Here are their implementations....
Notice that if a func takes exactly one arg, I don't have to curry it in order to use it in a functional pipeline.
Finally, the functional pipeline can be executed like this...
You know that you can just write like this, right? :)
And that's a perfect example of currying, imho. Without any funky bindings :D
I have one question please answer it and clear my dillema:
//below is currying function
const sum = a => {
return (b) => {
return a+b;
}
}
So my query is why we need to nest functions and make it currying? Why cant we simply define it as follow:
const sum = (a,b) => a+b;
In this way, we also pass a & b, whereas in first example we also pass a & b, then what is difference? What are advantages?
I didnt see anything about this, elaborate on this would be appreciated.
Thanks in advance!
Currying is also possible using .bind()
Hi guys!
I've been looking for a nice currying example and noticed few mistakes here. Just a few notes: sum(a,b,c) function provided last is not a best example of currying because currying is "single parameter at the time" (definitely not an add(20,90) etc), so sum(a,b,c) here is, probably, a good example of partial application. imho
Here are few interesting things described on wiki:
Wiki definition of curying: In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each take a single argument;
and partial application definition: In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity
p.s. this is just my imho :)
I found the great article which might help for understanding between currying and partial application:
2ality.com/2011/09/currying-vs-par...
The last part "To develop a function that takes a function and returns a curried function" was very confusing. What exactly happened there?