Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package example
- object week2Currying {
- def mapReduce(f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a: Int, b: Int): Int =
- if (a > b) zero
- else combine(f(a), mapReduce(f, combine, zero)(a + 1, b))
- //> mapReduce: (f: Int => Int, combine: (Int, Int) => Int, zero: 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
- sum(x=>x*x*x)(2,4) //> res0: Int = 99
- def factorial(n: Int): Int = product(x => x)(1, n)
- //> factorial: (n: Int)Int
- factorial(0) //> res1: Int = 1
- product(x => x*x)(3, 4) //> res2: Int = 144
- mapReduce(x => x * x, (x, y) => x * y, 1)(2, 4) //> res3: Int = 576
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement