Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active August 29, 2015 14:02
Show Gist options
  • Save kristopherjohnson/47a29ca479895c43815a to your computer and use it in GitHub Desktop.
Save kristopherjohnson/47a29ca479895c43815a to your computer and use it in GitHub Desktop.
curry() in Swift
// 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"
@kristopherjohnson
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment