Hi guys, a really introductory post on Clojure
Anyway. These sample
js codes come from the explanation I gave to a colleague at work. And pretty much worked to illustrate both cases.
To a beginner it might be not that easy to imagine how they will find room for using
apply. They think it will take millon years until it become useful. Wrong!
After listening to some “newbysh” considerations I came across the following code in Java Script, a well known language:
After reading this snippet. He instantaneously understood everything and how helpful
apply is. Wrapping up, …
… I told him:
Use apply for variadic functions. Functions you don’t know how many arguments it can take and you want to consider each element in a vector as if they were independent arguments. Or, even if you know how many args this function takes, for many times you’ll have vectors with values that matches arguments of a function.
For the second case it is easier to use destructuring, but it still applies.
Believe me, there are plenty ways to explain this. From the most scientific to the most simplistic. I would say below you are going to the a simplistic like explannation. But enough to bootstrap you with your clojure code.
After reading the snippet…
… he then came to an end:
morningis just reducing the
hellofunction surface, then exposing another function that takes one argument and forwards it to
hello, plus passing a constant predefined argument.
YES. That is it! But the most important question was: when should I use it?
Partial functions have a plenty use cases. To not make things “scientific” and keep then simple:
Imagine you are providing functions to someone else to query a database. You might create a base function that takes an enormous number arguments that actually assemble the queries. But you want to guarantee that certain fields/constraints/indexes are present on every query.
A good choice is to partially apply this base function with your prefixed well known safe arguments and then expose this produced function to your users.
There are much more use cases for partial functions. A good motivation is to make your code more legible and elegant. A good post on it was published by Christopher Maier right here.
Well, hope you liked the text and that it can help you faster understand things that may be left behind while studying it. See you!