Created
April 13, 2013 14:04
-
-
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
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
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