Sitemap
Soumendra Daas

Soumendra Daas

Providing Daas As A Service ...

Functionally Speaking

6 min readJan 17, 2016

A few months ago I was trying to analyze time-series data from splunk logs. After some head-banging (remember that hair-pulling is not an option for me) and significant cursing, I went looking for a “developer-friendly” way for processing event streams, and found Riemann. Riemann uses Clojure — a Lisp-based language that runs on the JVM, and allows developers to easily filter, combine, and perform other operations on event streams using functional programming concepts. I ended up spending the better part of December trying to understand functional programming concepts and how they could help developers be more productive.

This article is a summary of what I learned about functional programming, and why you might want care about it …

At this time, I also want to acknowledge and thank @redzedi and @ptrthomas who helped me in this journey, and helped make this article better.

The key attribute of a functional programming language is its ability to support higher-order functions — i.e., the ability to accept a function as a parameter to a function, and return a function as the result. Functional programming relies on a composition of functions in order to do its job. In this context, we should think of a “function” not as a subroutine, but as a mathematical function whose output only depends upon the current input.

Consider for example, the problem : Given a list of numbers, find the sum of squares of all the odd numbers. The classic imperative solution looks like

var data = [1, 2, 3, 4, 5, 6];
var i;
var out = 0;
for (i=0; i<data.length; i++){
if (data[i] % 2 !== 0 ) {
out += data[i]*data[i];
}
}

A more functional approach leads to

var data = [1, 2, 3, 4, 5, 6];
var isOdd = function(x) { return (x%2 !== 0); };
var square = function(x) { return x*x; };
var add = function(x,y) { return x+y; }
var out = data.filter(isOdd).map(square).reduce(add);

The first approach leaves me dealing with all sorts of low-level details — initial values, guard conditions, etc. The code also seems monolithic — there does not seem to be any clear separation between the three parts of the problem statement (find numbers that meet a criteria, do something with each one, do something with the collection).

To me, the second solution seems more “natural” — in the sense that it is more in tune with how I would have mentally decomposed the original problem into smaller modules, solved each one, and put them back together for the overall solution. This ability to modularize and compose seems to be an immense advantage.

In the second approach, I feel that I am able to think at at higher level of abstraction — the “what” if you will, whereas in the first approach I feel being dragged down into implementation details — the “how”. Yet, the second approach feels a bit alien to many programmers. Perhaps its just because we have been doing it the other way for two decades. After all, most of us learned Java because that’s what everyone else was learning … :-)

This, of course, is a trivial example, but it does beg the question — if you were the one responsible for maintaining this codebase, which one would you rather be dealing with ?

Lisp-like programming languages such as Scheme and Clojure take this concept of modularization and composition to a completely new level. At a fundamental level, the humble “pair” is the foundation of all data structures. There are only three operations possible

  • cons : ( for construct ) that takes two arguments and returns a compound data structure called a “pair”
  • car : that returns the first element of this pair
  • cdr : that returns the second element of this pair

For example:

1 ]=> (define x (cons 10 “dog”))1 ]=> (car x) ;Value: 101 ]=> (cdr x) ;Value 14: “dog”

It can be shown (see “Structure and Interpretation of Computer Programs” book) that all data structures can be constructed using these three primitives.

Get Soumendra Daas’s stories in your inbox

Join Medium for free to get updates from this writer.

The solution to the above problem could be written in Scheme as

(define data (list 1 2 3 4 5 6))
(define (square x) (* x x))
(fold-right + 0 (map square (filter odd? data)))

This definitely looks weird at first ( hence why Lisp sometimes called Lots of Insanely Stupid Parentheses) but it is actually quite simple. All Lisp expressions have the same format — an opening parenthesis, followed by an operation, followed by one or more operands. So something like foo(a,b) in C/Java etc would be written as (foo a b ) in Lisp. This has some interesting implications — for one, there is no concept of operator precedence. Also this leads to very terse code.

In this example, we have used the map, filter, and reduce functions that are also provided by Scheme. How may we go about implementing these ? In JavaScript, we could write filter as …

var myfilter = function (f, data) {
var out = [];
var i=0;
for(i=0; i<data.length; i++) {
if( f(data[i]) === true ) out.push(data[i]);
}
return out;
};

Note that this code is using mutable data structures such as “out” and “i”. Functional programming languages, on the other hand, encourages the use of immutable data structures. Recursion is often used where imperative programming languages would have used loops. Here is one implementation of filter in Scheme.

(define (my-filter f items)
(cond
( (null? items) items)
( (f (car items)) (cons (car items) (my-filter f (cdr items))))
( else (my-filter f (cdr items)))
)
)

Note the use of higher-order functions, and the fact that the data never changes state (i.e., is immutable). If we “fix” the parentheses, the code would have looked like :

my-filter( f, items ) {
if( items is null ) return items
x = first(items) // the first item from the list
restOfListFiltered = my-filter(f, rest(items));
if( f(x) == true ) return append(x, restOfListFiltered)
else return(restOfListFiltered)
}

One of the really cool features of functional programming languages is the concept of lazy-evaluation. There are language-level constructs that allow us to define sequences whose elements are calculated only when needed.

Consider the following problem : Find the first Fibonacci number that is greater than 100. In Clojure we can write the solution for this as

; inefficient code to generate the nth Fibonacci number
(defn fibonacci
[n]
(if (< n 2)
n
(+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
;generate the first 10 fibonacci numbers
(map fibonacci (range 10))
; find the first fibonacci number > 100
(first (filter #(> % 100) (map fibonacci (range 1000))))

I don’t plan to cover Clojure in detail in this post, but at this time it is sufficient to know that Clojure is a dialect of Lisp. Let’s deconstruct the code above …

The range function generates a list of number (0 1 2 … 999). The map function applies the fibonnaci function to each element of this collection, and returns a lazy sequence of numbers. This sequence is then filtered to get all the numbers that are greater than 100, and finally we extract the first element of this list. Note that the funky #(> % 100) is nothing but an anonymous function that returns true when the input parameter is greater than hundred.

Since Clojure supports lazy evaluation, it actually never computes all the 1000 Fibonacci numbers — which means that this code executes really fast. This also makes Clojure eminently suitable for processing event streams — which are really nothing but infinite sequences of data.

In conclusion …

Functional programming languages such as stateless functions, higher-order functions, and lazy evaluation can use used to create highly modular and composable code, and basically help us be more productive. Whereas it is true that some languages such as Clojure lend themselves better to functional programming than others, it is possible to do functional programming in most languages — even Java. The fact that functional programming concepts are increasingly being adopted in mainstream ecosystems like Java is testimony to the hope it generates.

Having said this, it _IS_ hard to change habits that have been built over a decade or more — after all, how can we write code without for-loops ? But with some self commitment and self-discipline, it is possible to change and build new habits over time — bet you don’t use “GOTO” anymore. As a baby-step towards developing a functional programming mindset — the next time you are wading through code, just ask yourself — “could I rewrite this using a map, filter, or reduce?”. You might be surprised.

--

--