Skip to content

Instantly share code, notes, and snippets.

@npathai
Created August 10, 2014 16:06
Show Gist options
  • Save npathai/83c5d90042840c554a14 to your computer and use it in GitHub Desktop.
Save npathai/83c5d90042840c554a14 to your computer and use it in GitHub Desktop.
Practicing the currying lecture of Functional Programming in scala course on coursera.
object Currying {
def sum(f: Int => Int) : (Int, Int) => Int = {
def sumF(a: Int, b: Int) : Int = {
if(a > b) 0
else f(a) + sumF(a + 1, b)
}
sumF
}
def sumOther(f: Int => Int)(a: Int, b: Int): Int = {
if(a > b) 0 else f(a) + sumOther(f)(a + 1, b)
}
def sumInts = sum(x => x)
def sumCubes = sum(x => x * x * x)
def id = {x: Int => x}
def product(f: Int => Int)(a: Int, b: Int): Int = {
if(a > b) 1 else f(a) * product(f)(a + 1, b)
}
def factorial(x: Int) = product(y => y)(1, x)
def mapReduce(f: Int => Int, combine: (Int, Int) => Int, id: Int)(a: Int, b: Int): Int = {
if(a > b) id else combine(f(a), mapReduce(f, combine, id)(a + 1, b))
}
def fact(n: Int) = mapReduce(x => x, (y, z) => y * z, 1)(1, n)
def main(args: Array[String]) {
println(fact(3))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment