One of the mathematical properties of a function is that given the same input values it will yield the sam output value every time. In addition, there will be one unique value for every set of input values. This property is called referential transparency. A consequence of referential transparency is that when you compute the value of a function for a given set of input values, you can make a note of that output value and the input values (called memoizing) and the next time you want to know the value for that set of input values you can look it up. That is usually less work than computing the value every time you need it. Some functional languages are aware of this property and automatically memoize calls to functions that will benefit from it.
Another feature of functional languages is that they treat functions as first class elements. That means that functions can be passed as arguments to other functions. This is useful in creating higher level behaviors. For example, we can create a function called sort that accepts a function that compares two elements. Then, by changing the comparison function we can sort by ascending values with on comparison function, sort by descending values with a different comparison function, and so forth. We can even sort by several different attributes if you are sorting records. Basically your options are only limited by your imagination.
There is a technique that is often used in functional languages. It is called currying and is named after the mathematician Haskell Curry. When you create a curried function you define a function that associates fixed values to some of the parameters of a function. Then when the remaining parameters are supplied it returns the same value as would have been returned if all the parameters had been supplied at once. For example, you might have a function called “add” that takes the arguments “a” and “b” and returns the sum of “a” and “b”. You might notice that you often add 2 to other numbers. You could create a curried function “add2” that takes a single parameter “a”. “add2” adds two to “a” and returns the sum. This might sound like an odd way to do this but it gives the compiler opportunities to optimize the curried function. It also makes your code more concise and easier to read.
There are other advantages to functional programming. I’ll write about them in future blog posts. But I hope this post has piqued your interest enough to inspire you to look into functional programming. There are a number of different languages that offer functional features. If you are a fan of Java, you might check out Scala or Groovy. If you are a Python programmer, give Julia a look. I have been looking into Elm of late. It is an excellent introduction to functional programming.
Sweet dreams, don’t forget to tell the ones you love that you love them, and most important of all, be kind.