Last active
December 21, 2015 13:27
-
-
Save jonathan-beebe/bdd48245533725f0658f to your computer and use it in GitHub Desktop.
curried functions in Swift
This file contains 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
// Here is a manually curried function. | |
// maxA takes an int and returns a function, maxB, that takes an int and returns an int. | |
func maxA(a:Int) -> (Int) -> Int { | |
func maxB(b:Int) -> Int { | |
return a > b ? a : b | |
} | |
return maxB | |
} | |
// And here is the same function using Swift’s build-in curry fetaure. | |
// https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-XID_615 -> Curried Functions | |
func maxN(a:Int)(_ b:Int) -> Int { | |
return a > b ? a : b | |
} | |
let a = 50 | |
let b = 6 | |
maxA(a)(b) | |
maxN(a)(b) | |
// While contrived, this demonstrates partially executing max by storing | |
// the intermediate function and later calling it with the second paramater. | |
let getGreatestNumber = maxN(a) | |
getGreatestNumber(5) | |
getGreatestNumber(60) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment