Last active
August 29, 2015 14:02
-
-
Save kristopherjohnson/47a29ca479895c43815a to your computer and use it in GitHub Desktop.
curry() 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
// Credit: https://twitter.com/eridius/status/474990322506670080 | |
func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C { | |
return { a in { b in f(a, b) } } | |
} | |
func curry<A, B, C, D>(f: (A, B, C) -> D) -> A -> B -> C -> D { | |
return { a in { b in { c in f(a, b, c) } } } | |
} | |
func curry<A, B, C, D, E>(f: (A, B, C, D) -> E) -> A -> B -> C -> D -> E { | |
return { a in { b in { c in { d in f(a, b, c, d) } } } } | |
} | |
curry(+)(100)(2) // 102 | |
let addFour = curry(+)(4) | |
addFour(10) // 14 | |
import Foundation | |
func display(format: NSString, a: NSNumber, b: NSNumber) -> NSString { | |
let sum: NSNumber = a.integerValue + b.integerValue | |
return NSString(format: format, a, b, sum) | |
} | |
let displayFormula = curry(display)("%@ + %@ = %@") | |
let displayEnglish = curry(display)("The sum of %@ and %@ is %@") | |
displayFormula(200)(50) // "200 + 50 = 250" | |
displayEnglish(200)(50) // "The sum of 200 and 50 is 250" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit goes to Kevin Ballard: https://twitter.com/eridius/status/474990322506670080