Advertisement
Guest User

Curried Functions

a guest
Oct 7th, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.05 KB | None | 0 0
  1. // Scala Version
  2. // def mapR(f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a: Int, b: Int): Int = {
  3. //   if (a > b) zero
  4. //   else combine(f(a), mapR(f, combine, zero)(a+1, b))
  5. // }
  6.  
  7. // def productR(f: Int => Int)(a: Int, b: Int): Int = mapR(f, (x,y) => x*y, 1)(a,b)
  8.  
  9. // def sumR(f: Int => Int)(a: Int, b: Int): Int = mapR(f, (x,y) => x+y, 0)(a,b)
  10.  
  11. // sumR(x => x)(1,2)
  12. // productR(x => x)(3,4)
  13. // sumR(x => x+1)(1,2)
  14.  
  15.  
  16. // Swift Version
  17. func mapR(f: Int -> Int, combine: (Int, Int) -> Int, zero: Int)(a: Int, b: Int) -> Int {
  18.     if (a > b) { return zero }
  19.    
  20.     return combine(f(a), mapR(f, combine, zero)(a: a+1, b: b))
  21. }
  22.  
  23. func product(f: Int -> Int)(a: Int, b: Int) -> Int { return mapR(f, {(x, y) -> Int in return x * y}, 1)(a: a, b: b) }
  24.  
  25. func sum(f: Int -> Int)(a: Int, b: Int) -> Int { return mapR(f, {(x,y) -> Int in return x + y}, 0)(a: a, b: b) }
  26.  
  27.  
  28. println(sum( {(x: Int) -> Int in return x} )(a: 1, b: 2))
  29. println(product( {(x: Int) -> Int in return x} )(a: 3, b: 4))
  30. println(sum( {(x: Int) -> Int in return x + 1} )(a: 1, b: 2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement