First Class Functions


One of the core ideas of functional programming is that the function is a first-class citizen.
What does that mean? A functional programming language treats a function like any other value. So, if you can treat a function as a value, that means you should be able to do everything with the function that you can do with a value. There are three major operations that we can do with values.

  1. You can assign them to a variable.
  2. You can pass them as an argument to a function.
  3. You can return them from other functions.

Treating function as a value implies that you should be able to do above operations with a function as well. So, you can do following things with a first class function.

  1. You can assign a function to a variable.
  2. You can pass a function as an argument to another function.
  3. You can return a function from other functions.

If you can do these three things with a function, it is a first-class function. We need to look at some examples to get the real gist of the first-class functions.


Assign a function to a variable

The first line of the above code defines a Scala function. The code is simple. It takes an integer and returns the double value. The next line assigns the doubler function to a variable d. Finally, we can call the function using the variable.

Pass a function as an argument to another Scala function

The first line of the above code declares a Scala range collection. The second line makes a map method call on the range object and also passes the doubler function as a parameter.

Pass a function as an argument to another Scala function

The code shown above defines a function getOps. The first line Inside the body of the getOps defines a local function doubler. The second line defines another local function 'tripler.' Finally, the if expression returns an appropriate local function depending on the value of c. Later, we call the getOps function and assign the returned value to d. The variable d holds a function that we call as the last line. We have seen three examples for treating functions as a value.
Keep reading for more interesting functional concepts.


Read More

Pure Functions | Referential Transparency | Benefits of pure functions | First class functions | Higher order function | Anonymous functions | Immutability | Tail Recursion | Expressions in Scala | Lazy Evaluations | Pattern Matching | Closures

By Prashant Pandey -



You will also like: