Skip to content

Instantly share code, notes, and snippets.

@thoolihan
Created April 13, 2013 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thoolihan/5378526 to your computer and use it in GitHub Desktop.
Save thoolihan/5378526 to your computer and use it in GitHub Desktop.
currying mapreduce example from Martin Odersky's scala course on Coursera https://class.coursera.org/progfun-002/lecture/37
package week2
object product {
def mapReduce(map:Int=>Int, reduce:(Int,Int)=>Int, init:Int)(a:Int, b:Int): Int = {
if(a>b) init
else reduce(map(a), mapReduce(map,reduce,init)(a+1,b))
} //> mapReduce: (map: Int => Int, reduce: (Int, Int) => Int, init: Int)(a: Int, b
//| : Int)Int
def product(f: Int => Int)(a: Int, b: Int): Int = mapReduce(f,(x,y) => x*y,1)(a,b)
//> product: (f: Int => Int)(a: Int, b: Int)Int
def sum(f: Int => Int)(a: Int, b: Int): Int = mapReduce(f,(x,y)=>x+y,0)(a,b)
//> sum: (f: Int => Int)(a: Int, b: Int)Int
def fact(n:Int):Int = product(x=>x)(1,n) //> fact: (n: Int)Int
fact(4) //> res0: Int = 24
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment