Currying Functions for Animals (and a singing robot)

Currying is a Functional Programming technique that can improve your code readability, reduce it’s length, diminish bugs but most importantly, known for causing you to fall in love with your code often.

Why Currying?

Suppose we have this data structure:

And suppose we must use selectAnimal() if we want to peek from the data structure, this can be reasonable if the structure is not exposed to us, or it is much more complex or large…

How can we take care of every animal in the zoo?
A procedural way to code it would be:

But this code has many disadvantages and duplicated segments that are not reused. Imagine what would happen if the list of animals was much longer. Of course we could loop over each type, but still the word zoo, for instance would appear several times. One could argue that zoo could have been a global variable for the function selectAnimal() but I disagree because I’d rather keep selectAnimal() a Pure Function for many reasons.

Notice the “salmon reptile” bug that is hiding like a needle inside a haystack in the code above.

Currying could help us solving these issues.

What is a Currying Function?

A Currying Function is converting a function with multiple arguments to a series of functions each accepts 1 argument, where each wraps the other. For example
(x, y, z) => z + y + z curried, would have been written like this:
x => y => z => x + y + z.
When you call it and send x, you get a function that accepts y, when y is sent, you get a function that accepts z, when z is sent then the answer returns.

How to Curry?

Lets use some Wrapper Functions on selectAnimal() and create a Currying Function:

or simply:

The entity above can be used in several ways:

Lets use this Currying Function to refactor the care taking code into something nice and less verbose.

Notice that the “salmon reptile” bug is less likely to happen in this code.

If we wanted to increase the reusabillity (degree of code reuse), a functional way to do so would be to create a high-order function like:

A high-order function is simply a function that either accepts a function as a parameter, or return a function or both.

The function takeCareMulti() is designed to take care of multiple animals, it accepts a typeSelector function, a typeCare function, and a list of animal names. Needless to say, It takes care on each animal.

Usage:

Notice the improvement from where we started. It is almost as if a robot is singing it. One could easily wrap each function to output its action and it would look like:

Summary

Use currying functions to increase code readability, reusabillity and your affection for the code. It might also decrease the length of your code and the chance to make a mistake.

where was that tiger all along?

namer

Out beyond ideas of wrongdoing
and rightdoing there is a field.
I’ll meet you there.

Rumi

ripple

Liked the article?

Subscribe

How to never use loops again with map, filter and reduce?

Here is a piece of code, it’s purpose is to manage employees’ salary bonuses due to holidays.

Was it ugly? Was it difficult to follow? Were there too many variables? And isn’t it too much verbose? The main problem with this code is that it is not straight to the point.

Lets refactor it so it could lose some sense of repetitiveness.

Replacing loops with map filter & reduce

Here is an alternative nice code:

I successfully eliminated any usage of loops. Notice how short it is. Notice that we got rid of variables such as extra, newEmps and others. The code is less verbose, it is straight to the point.

Now let’s dive deep on how each of the function refactored, so we could have some better understanding on map, filter & reduce.

Filter

Filter loops over a list and checks each item with a predicate function. If the function returns true, the item remains, otherwise it is filtered. An example:

Boys are persons who are children and males.

If you are not familiar with arrow functions whey are kinda nice, a synonym statement would have looked like this:

Map

Map loops over a list and apply a function on each item. All of the results are collected into a new list that returns. An example:

Men are grown boys.

Notice that hopefully grow is a pure function and thus, boys and men are two different lists.

Reduce

Reduce loops over a list and returns a single value out of it. Depending on an iteratee function sent, reduce sums, multiplies or does any other operation. Example:

In the example above, if population consists of 4 people, then iteratee function would have been called 4 times. In other words, if we called the ireratee function countSavings, for the sake of example, then the above reduce function produces the same value as this code:

Bonus Section – How to avoid looping over functions?

If some of the things are still unclear at this point, it is a good idea to read again the salary example refactored and examine it a little further.

Lets go back to our salary example above. Say that salary calculation task was way more complex, in fact it is. If in order to calculate it, we would need a vast amount of functions, how would we do it?

Assuming emp has an array of salary transactions, something like:

Then surely we had to loop over this functions and

Don’t be so sure. There is also a way to eliminate this loop away. Read carefully and twice:

Lets examine the expression above, beginning with (arg, func) => func(arg):
This function accepts two parameters, first is an argument, second is a function. The return value is that which the function (2nd parameter) will return when given the arugment (1st parameter). So for instance, if we call this weird entity kindDavid just for the sake of example, then:
kingDavid(3,x=>x+4) is 7
and
kingDavid(13.5,x=> x==13.5) is true
and more importantly
kingDavid(emp, calculateSalary) is calculateSalary(emp)

Because calculateSalary is a function returning a new emp object it can work perfectly with reduce. First iteration will apply: (emp, emp.transactions[0]) which will return emp.transactions[0](emp). This is actually a new emp with calculated salary. It is now to be sent as a first argument in (result, emp.transactions[1]), which will return emp.transactions[1](result), and so on… Until all the transaction functions applied on a single emp.

The below code emphasizes it:

Want to know more?

Hit

npm install lodash --save

Then

const _ = require('lodash');

And play with it. Full documentation is here.

Summary

If you don’t like your code too straight to the point, use loops.

Subscribe

How to write Wrapper Functions? (aka Decorators)

Wrapping a function, also known Decorating, is parallel to inheriting from an object in the OOP world. It is a way of taking a prototype idea and extend it in a way that encourages code reuse. Moreover, it is a powerful creative tool that open doors to new ways of coding and thinking.

Say we developed a Server that logs many messages like

But it is only after we coded that we realized we forgot to log the actual time of the message. First thing that comes to mind is that the code needs to get refactored, and any appearance of console.log should be replaced with some other function that logs the time as well. This is probably the right thing to do by the way, but for the sake of curiosity wouldn’t it be nice if we could just alter console.log?

Altering console.log

Meet wrapper:

Wrapper is a function that accepts a function as a parameter and returns a function when its done. This makes it a Higher-Order Function, which is the title any function that gets or returns a function earns. The way to use wrapper in our Server is:

console.log = wrapper(console.log);

What just happened here? Lets begin from the right side of the expression, we just sent console.log as a parameter to some wrapper. Wrapper received the function, and in return, it gave back a new function. One that first prints the date, and then invokes the parameter function. The returned function eventually is set back to be console.log itself.

Note the use of console.info in the wrapper. If we used console.log to log the date, it wouldn’t work because by the time it invokes console.log is referring the wrapper, but if the wrapper is within in itself.. it means.. – – – > INFINITY !

Note that the parameter func is accessible inside the new function that is being created, and also available in the time of invoking the inner function (which turns to be console.log). This is due to Closures. In a sentence, any function, at the moment of creation, takes a snapshot of its scope which will remain available at the moment of running. This is called Closure since the scope lives just because it has a reference which is the very function that this scope actually belonged to in first place.

What a closure 🙂

Read that sentence again.

This concept also gives the opportunity for this freak to actually work:

If you are wondering how to use it, this is the way:

But you can also go straight forward:

Last Note
Wrapping a function doesn’t necessarily have to do with mutating existing functions. We could also use wrapping as a function inheritance technique.

This might actually be a more common way, but I just wanted to show off.

For more info see Decorators.

How to write Pure Functions

A pure function is a function where the return value is only determined by its input values, without observable side effects. This is how functions in math work: Math.cos(x) will, for the same value of x , always return the same result

– Wikipedia

Pure Functions fulfill the KISS principle (Keep It Simple & Stupid), Using them in coding can reduce dramatically the complexity of your code. Basically all one has to do is avoiding 2 main mistakes.

1. Not Ecologic

When a function carry side effects, it may become challenging to predict the outcome of invoking it. In many cases, other team member may use our function, not knowing the side effect that will take place. This can cause much confusion. Iv’e seen functions that carry so many side effects that it was extremely challenging to understand how to maintain them.


// Bad example:
function getNewDog() {

   // Create Dog
   var newDog = DogFactory.createDog("woof!");

   // Add it to Golbal list [not ecologic!]
   owner.dogs.push(newDog);

   // Return the dog
   return newDog;
}

In the example above, the owners’ list is altered because this is the programmer intention. But the function name doesn’t reveal it’s hidden affects. A pure way to write this function would be:


// Good example:
function getNewDog() {

   // Create Dog, and return it
   return DogFactory.createDog("woof!");
}

// Add to list
owner.dogs.push(getNewDog());

2. Not Independent

When the value is not determined only by the parameter, a function might be unpredictable of value. It also might cause Error if it runs in foreign scopes. And on top of that, it limits the function to be too specific to task.


// Bad example:
function getHealthyDog() {

   // For each dog of Global owner [Not Independent]
   for(var dog of owner.dogs) {

     // If the dog is healthy
     if(dog.healthy) {

       // Return it
       return dog;
     }
   }
}

The function above is dependent on owner. If the owner changes, the value of the function changes. If the owner is undefined the function throws error. A Pure way to write it would be:


// Good example:
function getHealthy(list) {

   // For each item in list
   for(var item of list) {

     // If the item is healthy
     if(item.healthy) {

       // Return it
       return item;
     }
   }
}

getHealthy(owner.dogs);

Note that by making the function purer, we enlarged it’s purpose and made it abstract. Now it doesn’t yield a healthy dog, but any object that could be identified as healthy.

Pure functions are easy to learn and adopt. They will make your life easier.