Advertisement
jules0707

week2Currying

Feb 27th, 2017
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.11 KB | None | 0 0
  1. package example
  2.  
  3. object week2Currying {
  4.  
  5.   def mapReduce(f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a: Int, b: Int): Int =
  6.     if (a > b) zero
  7.     else combine(f(a), mapReduce(f, combine, zero)(a + 1, b))
  8.                                                   //> mapReduce: (f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a: Int, b:
  9.                                                   //|  Int)Int
  10.  
  11.   def product(f: Int => Int)(a: Int, b: Int): Int =
  12.     mapReduce(f, (x, y) => x * y, 1)(a, b)        //> product: (f: Int => Int)(a: Int, b: Int)Int
  13.  
  14.  
  15.   def sum (f:Int=>Int)(a:Int,b:Int):Int =
  16.   mapReduce(f, (x,y)=>x+y, 0)(a, b)               //> sum: (f: Int => Int)(a: Int, b: Int)Int
  17.  
  18.   sum(x=>x*x*x)(2,4)                              //> res0: Int = 99
  19.  
  20.   def factorial(n: Int): Int = product(x => x)(1, n)
  21.                                                   //> factorial: (n: Int)Int
  22.   factorial(0)                                    //> res1: Int = 1
  23.  
  24.   product(x => x*x)(3, 4)                         //> res2: Int = 144
  25.   mapReduce(x => x * x, (x, y) => x * y, 1)(2, 4) //> res3: Int = 576
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement