Skip to content

Instantly share code, notes, and snippets.

@ajjain
Created November 19, 2013 03:37
Show Gist options
  • Save ajjain/7539921 to your computer and use it in GitHub Desktop.
Save ajjain/7539921 to your computer and use it in GitHub Desktop.
Higher Order Function in Scala Explained. This example is taken from Martin Odersky's teaching at Coursera.
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment