Last active
August 29, 2015 14:07
-
-
Save oreillyross/33435ea229bb5d548789 to your computer and use it in GitHub Desktop.
Currying examples. Used in Scala mainly for type inference algorithms
This file contains hidden or 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
def sum(x: Int)(y: Int)(z: Int) = x + y + z | |
val curriedWithMultipleArguments = sum _ | |
val addToNine = curriedWithMultipleArguments(4,5) | |
addToNine(3) |
This file contains hidden or 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
// 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) |
This file contains hidden or 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
// 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