Tuesday, February 28, 2017

Scala : Higher order functions , currying , anonymous in functional programming






package com.salpe.scala

object HigherOrderFunctions {

  // define functions like field 
  def identity(x: Int) = x

  def main(args: Array[String]): Unit = {

    // passing declared function as argument 
    println(sumInts(identity, 0, 10))

    // passing anonymous function as argument 
    println(sumInts(x => x, 0, 10))
    println(sumInts(x => x * x, 0, 10))
    println(sumInts(x => x * x * x, 0, 10))

    // Currying 
    println(summationOf(cube)(0, 10))

    println(sumOfCubeOfInts(0, 10))

  }

  // defining functions as local variables  
  def cube(x: Int): Int = x * x * x

  // Passing function as argument 
  def sumInts(f: Int => Int, a: Int, b: Int): Int = {
    if (a > b) 0 else f(a) + sumInts(f, a + 1, b)
  }

  // Defining function inside function 
  def sumOfCubeOfInts(a: Int, b: Int): Int = {
    def myCube(x: Int): Int = x * x * x
    if (a > b) 0 else myCube(a) + sumOfCubeOfInts(a + 1, b)
  }
  // Returning function as argument  
  def summationOf(f: Int => Int)(a: Int, b: Int): Int = {

    def sum(a: Int, b: Int): Int = {
      if (a > b) 0 else f(a) + sum(a + 1, b)
    }

    sum(a, b)
  }


}

No comments: