Created
August 10, 2014 16:06
-
-
Save npathai/83c5d90042840c554a14 to your computer and use it in GitHub Desktop.
Practicing the currying lecture of Functional
Programming in scala course on coursera.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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