Scala - Thinking of functions as transformers

When you write Scala code like this:

val x = List.range(1, 10)
val evens = x.filter((i: Int) => i % 2 == 0)

the following portion of the code is a function literal (also known as an anonymous function):

(i: Int) => i % 2 == 0

When reading this code, it helps to think of this symbol:

=>

as a transformer. In this example, it transforms the parameter list on the left side of the symbol (an Int named i) into a new result using the algorithm on the right side of the symbol (in this case, an expression that results in a Boolean).

A calculus “function as a transformer” image

Last night I was reading a fun calculus book, The Cartoon Guide to Calculus , and found that the author, Larry Gonick, used an image that I had in mind about how Scala functions and the => symbol work as transformers:

Scala functional programming - functions as transformers

While some people might not like that image, it shows exactly what a pure function does: It takes some input, does something to it, and produces an output. It transforms the input into the output.

If you’re having any problems with functional programming at all, I highly recommend reading the first 15-20 pages from this book. The images Mr. Gonick uses really help to explain calculus, and in the process, explains how functions transform inputs into outputs.