Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Last active August 29, 2015 14:07
Show Gist options
  • Save oreillyross/33435ea229bb5d548789 to your computer and use it in GitHub Desktop.
Save oreillyross/33435ea229bb5d548789 to your computer and use it in GitHub Desktop.
Currying examples. Used in Scala mainly for type inference algorithms
def sum(x: Int)(y: Int)(z: Int) = x + y + z
val curriedWithMultipleArguments = sum _
val addToNine = curriedWithMultipleArguments(4,5)
addToNine(3)
// defining a method using def for a curried function
def plusMethod (a: Int)(b: Int) = a + b //> plusMethod: (a: Int)(b: Int)Int
val functions = List(1,2,3) map plusMethod //> functions : List[Int => Int] = List(<function1>, <function1>, <function1>)
//|
functions(0)(1) //> res2: Int = 2
// take the function (the underscore) and apply it to the number 5
functions map {_ (5) } //> res3: List[Int] = List(6, 7, 8)
// demonstrating function currying
val plus = {(a: Int, b: Int) => a + b } //> plus : (Int, Int) => Int = <function2>
// the inner function, a value is a closure
val plusCurry = { a: Int => { b: Int => a + b } }
//> plusCurry : Int => (Int => Int) = <function1>
val plus1 = plusCurry(1) //> plus1 : Int => Int = <function1>
plus1(2) //> res0: Int = 3
plusCurry(1)(2) //> res1: Int = 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment