Welcome back to part two of functional programming. In the last article, I discussed some of the core concepts of functional programming. This week, I will discuss a few more fundamental concepts and next week I will wrap up by talking about where and how FP is used.


Currying is the idea of taking a function that needs multiple arguments, and breaking it up into multiple, nested functions where each takes only one argument.

The idea of currying comes from the world of mathematics; the idea being that functions are easier to reason about if there is only parameter. You probably remember this concept from Algebra where you broke up f(x, y) into f(x)f(y) and so on.


Since functional programming is based off of pure functions which simply take an input and return an output and don't affect anything outside of their own function scope, we can make the assumption that given the same input, we will always get the same output. This let's us cache, or memoize, the results of the function: If we pass in an input to a function once, we can cache the result, and in the future, use the cached result instead of running the whole expensive function all over again.


Other types of programming generally use loops to iterate through items. In a functional style of programming, functions call themselves over and over again until an exit condition is met. You can also have multiple functions calling each other recursively which is called 'mutual recursion.'


In a purely functional language like Haskell, you can have recursive functions that call themselves as many times as you need and it won't add onto the call stack because it recognizes that it's just a single function calling itself. The compiler/interpreter knows what to expect in terms of variables inside of the function. In JavaScript, there is a limit to the number of times that a function can call itself because it adds every function call onto the call stack, even if it's the same function over and over again; usually this limit is few thousand recursive calls, depending on the JavaScript environment/browser.

Thus, in a language like JavaScript, you have to be careful using recursion. It can still be used as a more simple and elegant solution to some problems but only when you are certain that the number of function calls will fall within the limit. Otherwise, you will see an error like this:

Note: There is a specification to implement 'proper tail-call recursion' - recursive calls that are made at the end of a function in the return statement and only one function call to the stack - in JavaScript, but it has not been widely adopted as of the writing of this article.

What do you think of these mini articles? Leave a comment and let me know.

See you next week!