Saturday, December 6, 2014
Scala is also a functional programming language and allows the definition of higher order functions. Functions that take other functions as parameters or whose result is a function are called higher order functions (HOF). In Scala functions are treated as first class values which can be passed as parameters and returned as a result.

Let us look at some simple examples to understand Scala higher order functions.

Higher Order Function - Function as a parameter

In this example we have a higher order function compute which takes a function as a parameter. Here 'f' is a function which takes two arguments of type Int and returns an Int.

f : (Int, Int) => Int

The higher order function takes another function 'f' and values 'arg1' and 'arg2' as input and applies function 'f' to the values 'arg1' and 'arg2'.

object HigherOrderFunctionTest {
    
  def sum ( a : Int, b: Int ) : Int = { a + b }
  def sub ( a : Int, b: Int ) : Int = { a - b }
  def mult ( a : Int, b: Int ) : Int = { a * b } 
  def div ( a : Int, b : Int ) : Int = { a / b }
  
  // Higher order function
  def compute(f : (Int, Int) => Int, arg1: Int, arg2 : Int) : Int = {
    if ( arg1 > 0 && arg2 > 0 )
      f(arg1, arg2)
    else
      0
  }
  
  def main(args: Array[String]) {
    println(compute(sum,20,10))
    println(compute(sub,20,10))
    println(compute(mult,20,10))
    println(compute(div,20,10))
    println(compute(div,20,0))
  }
}

Higher Order Function - Function as a result

In this example we have a higher order function which returns a function as a result. The higher order function giveMe takes a String as input and returns a function which takes two Int's as input and returns an Int represented as (Int, Int) => Int.

object HigherOrderFunctionTest1 {

  // Higher order function
  def giveMe(t : String) : (Int, Int) => Int  = t match {
    case "sum" => (x, y) => x + y
    case "sub" => (x, y) => x - y
    case "mult" => (x, y) => x * y
    case "div" => (x, y) => x / y
  }

  def main(args: Array[String]) {
    println(giveMe("sum")(20, 10))
    println(giveMe("sub")(20, 10))
    println(giveMe("mult")(20, 10))
    println(giveMe("div")(20, 10))
  }
}

Proceed to read other Scala Tutorials.

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top