Scala - High Order Function (Function as parameter or return object)

Card Puncher Data Processing

About

Higher order functions are functions that take a function as a parameter or return functions.

Functions in functional programming are higher order functions since following actions can be performed with them.

  • Functions can be passed within functions as arguments.
  • Functions can be created within functions just as objects can be created in functions
  • Functions can be returned from functions

Example

// sum() returns a function that takes two integers and returns an integer  
def sum(f: Int => Int): (Int, Int) => Int = {  
  def sumf(a: Int, b: Int): Int = {...}  
  sumf  
} 

// same as above. Its type is (Int => Int) => (Int, Int) => Int  
def sum(f: Int => Int)(a: Int, b: Int): Int = { ... } 

// Called like this
sum((x: Int) => x * x * x)          // Anonymous function, i.e. does not have a name  
sum(x => x * x * x)                 // Same anonymous function with type inferred

def cube(x: Int) = x * x * x  
sum(x => x * x * x)(1, 10) // sum of cubes from 1 to 10
sum(cube)(1, 10)           // same as above     

Function as parameter

val numbers = List(1,2,3,4,5,6,7,8,9,10)
val total = numbers.foldLeft(0){(a,b) => a+b }

where the unction “foldLeft” is provided by Scala library on collections.





Discover More
Card Puncher Data Processing
Scala - Function

See Higher order functions are functions that take a function as a parameter or return functions. Call by value: evaluates the function arguments before calling the function Call by name: evaluates...



Share this page:
Follow us:
Task Runner