What is function composition?
Function composition is the combing of two or more functions to make another entirely new function.Functions are treated like parts that can be combined to make new parts that process data in new ways. The concept is really powerful and useful.
Let's look at a quick example:
In the above function we first define two binary functions ( a function that takes two inputs ). Then we define a function
compose that takes two functions as arguments
g, when then return a function that takes three arguments that are then passed to the binary functions that are accessible via closure.
Using functions in this way means that we can snap together the parts we need and make functions that do the work for us, many times the same basic functions can be reused over and over again saving rewriting a new function from scratch.
Have a look at these example and you will start to get a feel for how functions can be used together to make new ones:
In this example we take a param double it and then square the result by its new value. So in this case 5 gets added to itself to make 10, which is then squared by itself to make 100. Study the code and try to really see what is happening, there are comments to make things a little clearer.
Here we are defining a function to keep an index within a range, you can see that we use two functions called
to to eventually create the final
fromTo functions which keep the track of the numbers. A pillar of functional programming is to let the functions do the work, if you have something that is already written and can be utilized in making another function you need, then use it.
This one may be a little harder to follow, I was mainly just playing around with different concepts including currying which is something I will examine further in a future post.
Some additional resources: