What are Higher Order Functions? Scala and Python Approach

Hi guys,

In this post I’ll be discussing about higher order functions with examples in Scala and Python. This will be gentle introduction. It shall however help you to move on to more advanced concepts in higher order functions.

What are higher order functions?

Before understanding higher order functions, let’s just recall about functions. We know that functions are programming construct that are a block of code, a module or a collection of code to do something. These are constructed to do a particular task and can take any other data as arguments and return some data as arguments. In most of the languages, we see that to be able to pass argument or return result, we need to use some data type. That data type can be string, number or any instance of some class.

def increaseByTwo(num):
   return num + 2

def doSomething(array, func):
   return list(map(func, array))

print(doSomething([1, 2, 3, 4], increaseByTwo))

In the above code, we can see two functions, increaseByTwo and doSomething. First one is a normal function as we’ve understood from our early days of programming while second one is a bit different. It takes a function as an argument and applies that to an array of numbers. Such functions that take some other function as argument or return the function are called higher order functions. Normal functions cannot take functions as arguments or return function as results while higher order functions can. Scala version of above code is:

def increaseByTwo(num:Int) = num + 2

def doSomething(l:List[Int], func: Int => Int) = l.map(increaseByTwo)

println(doSomething(List(1,2,3,4), (x:Int) => x + 2))

We can return functions as result of function, both in Python and scala. See the code below.

Python:


def getFun():
    def computeSqr(num):
        return num ** 2

    return computeSqr

print(getFun()(7))

Scala:

  def getFun: Int => Int = {
      def computeSqr(num: Int) = num * num
      computeSqr
    }

  print(getFun(7))

In the above code, we can see that function getFun returns a function that takes number as input and returns square of that number as result. That returned function in turn takes 7 as argument and returns square of 7 as result.

We can combines these powerful constructs in various ways to improve program conciseness and expressiveness. Related articles to follow soon.

I hope this gentle introduction was helpful to you. Please feel free to comment in case of any queries/suggestion. See you in the next one.

Cheers 🙂

122 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *