If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Tuesday, July 30, 2013

Curried functions and partially applied functions

package functions
import scala.math.pow
object CurriedFunctionDemo {
/**
* A partially applied function is a function where some of its arguments have
* already been filled in.
*/
//a*x^2 + b*x + c
def nonCurriedFormula(a:Int, b: Int, c:Int, x: Int): Double = a * pow(x, 2) + b * x + c
//a*x^2 + b*x + c
def curriedFormula(a:Int)(b:Int)(c:Int)(x:Int): Double = a * pow(x, 2) + b * x + c
def main(args: Array[String]): Unit = {
//3*x^2 + 4*x +5
val formula1 = curriedFormula(3)(4)(5)(_)
println(formula1(1)) //should print 12
println(formula1(2)) //should print 25
println(nonCurriedFormula(3,4,5,2)) //should print 25
val nonCurriedToCurried = (nonCurriedFormula _).curried
val formula2 = nonCurriedToCurried(3)(4)(5)
println(formula2(1)) //should print 12
}
}
/** output console
12.0
25.0
25.0
12.0
**/
view raw gistfile1.scala hosted with ❤ by GitHub

No comments:

Post a Comment