Created
January 9, 2013 04:31
-
-
Save maxdeliso/4490589 to your computer and use it in GitHub Desktop.
higher order functions and nested recursive lambdas in Scala
This file contains hidden or 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
/* | |
* Max DeLiso <[email protected]> | |
* 1/8/13 | |
* higher order functions and nested recursive lambdas in Scala | |
*/ | |
package lesson4 | |
object currying { | |
def mapReduce( | |
f: Int => Int, | |
combine: (Int, Int) => Int, | |
zero: Int): (Int, Int) => Int = { | |
(a: Int, b: Int) => | |
{ | |
if (a > b) zero | |
else combine(f(a), mapReduce(f, combine, zero)(a + 1, b)) | |
} | |
} | |
def sum(f: Int => Int)(a: Int, b: Int): Int = | |
mapReduce(f, (a, b) => a + b, 0)(a, b) | |
def product(f: Int => Int)(a: Int, b: Int): Int = | |
mapReduce(f, (a, b) => a * b, 1)(a, b) | |
def factorial(n: Int): Int = { | |
product(x => x)(1, n) | |
} | |
def main(args: Array[String]) = { | |
Console.println("1 + ... + 10 = " + sum((x => x))(1, 10) + "\n" + | |
"1 * ... * 10 = " + product((x => x))(1, 10) + "\n" + | |
"10! = " + factorial(10) + "\n" + | |
"1 + 2 + 3 = " + mapReduce((x => x), (a, b) => (a + b), 0)(1, 3)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1 + ... + 10 = 55
1 * ... * 10 = 3628800
10! = 3628800
1 + 2 + 3 = 6