Higher Order Functions in Scala

Reading Time: 3 minutes

Introduction:

Some functions are called higher-ordered functions as they accept functions as parameters. You can also have a higher-order function as one that returns the functions. So basically, if there is a function that deals with a function, is kind of a meta-level, we call it higher order.

Why do we use higher order functions..??

Because we want to be able to reuse our code over and over again on different parameters (functions that the code calls) and to simplify the structure/organization/readability of our program by abstracting the implementation of a potentially complicated algorithm away from its use.

So the function that we are doing here is a way of generalizing the combining of three numbers. So let’s consider some little examples.

def sum(x:Double, y:Double, z:Double):Double => x+y+z

Another way to combine three numbers would be multiplication. And so defining something which is very similar to addition, that is multiply.

def multiply(x:Double, y:Double, z:Double):Double => x*y*z

Another way to combine three numbers would be to find the minimum among the three. We can write it using min as the operator.

def min(x:Double, y:Double, z:Double):Double => x min y min z

And we can see the results below.

sum(1,2,4)
Double = 7.0

multiply(3,2,4)
Double = 24.0

min(1,3,6)
Double = 1.0

Now, I would like to do all these functions and possibly others and combine them into one single function and call it as combine.

In addition to these value arguments, I also need the function I am going to use to combine them. Let’s call it f. Just like others, we have to specify the type here as well and this function takes two doubles and gives us back a double.

scala> def combine(x:Double,y:Double,z:Double,f:(Double,Double)=>Double):Double = f(f(x,y),z)
def combine(x: Double, y: Double, z: Double, f: (Double, Double) => Double): Double

Let’s see the output.

scala> combine(1,2,3,(x,y)=>x+y)
val res0: Double = 6.0

And it is working fine. It can also be written in the format as shown below because these two are equivalent.

scala> combine(1,2,3,_+_)
val res1: Double = 6.0

scala> combine(2,4,6,_*_)
val res4: Double = 48.0

This is a simple example of a higher-order function. And it is a higher-order function because it takes one of its arguments which has a function type and this function type is specified as shown above. This gives a brief introduction to higher-order functions and shows us how we can use these things.

The commonly used higher-order functions in Scala are map, flatMap, filter, etc. The simple examples are as below.

map:

scala> val subject = Vector("MATHS","ENGLISH","SCIENCE")
val subject: scala.collection.immutable.Vector[String] = Vector(MATHS, ENGLISH, SCIENCE)

scala> subject.map(sub => sub.toLowerCase)
val res1: scala.collection.immutable.Vector[String] = Vector(maths, english, science)

flatMap:

scala> Seq("Hi","This is about","higher order functions").flatMap(s => s.split(" "))
val res1: Seq[String] = List(Hi, This, is, about, higher, order, functions)

filter:

scala> val names = List("Hi","this","blog","explains","higher","order","funcitons")
val names: List[String] = List(Hi, this, blog, explains, higher, order, funcitons)

scala> val seqNames = names.filter(name => name.length > 2)
val seqNames: List[String] = List(this, blog, explains, higher, order, funcitons)

scala> val seqNames = names.filter(name => name.length > 4)
val seqNames: List[String] = List(explains, higher, order, funcitons)

Some important points about Higher order functions:

  • It is beneficial in producing function composition where, functions might be formed from another functions. The function composition is the method of composing where a function shows the utilization of two composed functions.
  • It is also constructive in creating lambda functions or anonymous functions. The anonymous functions are the functions which does not has name, though perform like a function.

Conclusion:

This topic will be used in plenty of useful places in your code. Higher-order is an important concept and easy to master as well. So, I would say, keep practicing. That’s all basic I have in my mind as of now, related to higher-order functions best practices, which could be understood by any beginner level programmer. The language does not matter. You can write in any language you want to write.

So, focus on the logic. If you found anything missing or you do not relate to my view on any point, drop me a comment. I will be happy to discuss. For more blogs, click here

References:

https://docs.scala-lang.org/tour/higher-order-functions.html

https://www.geeksforgeeks.org/higher-order-functions-in-scala/

Written by 

Rituraj Khare is a Software Consultant at Knoldus Software LLP. An avid Scala programmer and Big Data engineer, he has experience with the tech stack such as - Scala| Spark| Kafka| Python| Unit testing| Git| Jenkins| Grafana.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading