Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Created January 9, 2013 04:31
Show Gist options
  • Save maxdeliso/4490589 to your computer and use it in GitHub Desktop.
Save maxdeliso/4490589 to your computer and use it in GitHub Desktop.
higher order functions and nested recursive lambdas in Scala
/*
* 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))
}
}
@maxdeliso
Copy link
Author

1 + ... + 10 = 55
1 * ... * 10 = 3628800
10! = 3628800
1 + 2 + 3 = 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment