Tuesday, November 19, 2013

Higher Order Functions

What does it mean by functions as first class values? Or, what are higher order functions?

There are languages which supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures. Scala is one such language which does support higher order functions, scala worksheets below explains some of these with examples:

package learn.scala
object Exercise {
println("Welcome to the Exercises") //> Welcome to the Exercises
// EXERCISE 1:
// Write a product function that calculate product of values of a function for the points
// on a given interval
def prod(f: Int=>Int, a: Int, b: Int): Int = {
if(a > b) 1 else{
f(a) * prod(f, a+1, b)
}
} //> prod: (f: Int => Int, a: Int, b: Int)Int
prod(x=>x, 1, 5) //> res0: Int = 120
// EXERCISE 2:
// Write Factorial in terms of product
def factorial(a: Int): Int = {
prod(x=>x, 1, a)
} //> factorial: (a: Int)Int
factorial(10) //> res1: Int = 3628800
}
view raw ScalaExample.sc hosted with ❤ by GitHub

package learn.scala
object Exercise {
// Exercise on implementing Higher order functions in Scala.
// All these examples are taken from Martin Odersky teachings on coursera.
// EXERCISE 1:
// Write a product function that calculate product of values of a function for the points
// on a given interval
def prod(f: Int => Int, a: Int, b: Int): Int = {
if (a > b) 1 else {
f(a) * prod(f, a + 1, b)
}
} //> prod: (f: Int => Int, a: Int, b: Int)Int
prod(x => x, 1, 5) //> res0: Int = 120
// EXERCISE 2:
// Write Factorial in terms of product
def factorial(a: Int): Int = {
prod(x => x, 1, a)
} //> factorial: (a: Int)Int
factorial(10) //> res1: Int = 3628800
//==============================================================================================
// EXERCISE 2:
// finding a fixed point of function example
// x, f(x), f(f(x)),f(f(f(x))),....
// until value doesn't vary any more
// first fixed point value f(x) = 1 + x/2
//---------- my version
def fixedPoint(f: Double => Double)(x: Double): Double = {
def abs(y: Double): Double = if (y > 0) y else -y
//println(x)
if (abs(x - f(x)) <= 0.0000001) f(x) else (fixedPoint(f))(f(x))
} //> fixedPoint: (f: Double => Double)(x: Double)Double
fixedPoint(x => 1 + x / 2)(1) //> res2: Double = 1.9999999403953552
// find square root using this definition of fixed point.
// definition of square root function interms of fixed point is as below:
// sqrt(x) is a fixed point of the function y = x/y
def sqrt(x: Double): Double = fixedPoint(y => (y + x / y) / 2)(1)
//> sqrt: (x: Double)Double
sqrt(2) //> res3: Double = 1.414213562373095
}

No comments:

Post a Comment

StatCounter - Free Web Tracker and Counter