Created
November 21, 2014 18:49
-
-
Save kconner/eb1ef62edd0ff991a186 to your computer and use it in GitHub Desktop.
Currying, argument reordering, and partial function application in Swift
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
func curry<T, U, R>(binary: (T, U) -> R) -> T -> U -> R { | |
return { t in | |
return { u in | |
return binary(t, u) | |
} | |
} | |
} | |
func curry<T, U, V, R>(ternary: (T, U, V) -> R) -> T -> U -> V -> R { | |
return { t in | |
return { u in | |
return { v in | |
return ternary(t, u, v) | |
} | |
} | |
} | |
} | |
func curry<T, U, V, W, R>(quaternary: (T, U, V, W) -> R) -> T -> U -> V -> W -> R { | |
return { t in | |
return { u in | |
return { v in | |
return { w in | |
return quaternary(t, u, v, w) | |
} | |
} | |
} | |
} | |
} | |
func reorder<T, U, R>(curried: T -> U -> R) -> U -> T -> R { | |
return { u in | |
return { t in | |
return curried(t)(u) | |
} | |
} | |
} | |
func partial<T, U, R>(binary: (T, U) -> R, argument: T) -> U -> R { | |
return { u in | |
return binary(argument, u) | |
} | |
} | |
func partial<T, U, V, R>(ternary: (T, U, V) -> R, t: T) -> (U, V) -> R { | |
return { u, v in | |
return ternary(t, u, v) | |
} | |
} | |
func partial<T, U, V, R>(ternary: (T, U, V) -> R, t: T, u: U) -> V -> R { | |
return { v in | |
return ternary(t, u, v) | |
} | |
} | |
func partial<T, U, V, W, R>(quaternary: (T, U, V, W) -> R, t: T) -> (U, V, W) -> R { | |
return { u, v, w in | |
return quaternary(t, u, v, w) | |
} | |
} | |
func partial<T, U, V, W, R>(quaternary: (T, U, V, W) -> R, t: T, u: U) -> (V, W) -> R { | |
return { v, w in | |
return quaternary(t, u, v, w) | |
} | |
} | |
func partial<T, U, V, W, R>(quaternary: (T, U, V, W) -> R, t: T, u: U, v: V) -> W -> R { | |
return { w in | |
return quaternary(t, u, v, w) | |
} | |
} | |
let addThree = partial(+, 3) | |
let eight = addThree(5) | |
let curriedDivide: Int -> Int -> Int = curry(/) | |
let tenDividedBy = curriedDivide(10) | |
let two = tenDividedBy(5) | |
let divideByTen = reorder(curriedDivide)(10) | |
let four = divideByTen(40) | |
func printFourThings(thing1: String, thing2: String, thing3: String, thing4: String) { | |
println(thing1) | |
println(thing2) | |
println(thing3) | |
println(thing4) | |
} | |
let greetTheWorldAnd = partial(printFourThings, "hello, world", "and") | |
greetTheWorldAnd("let's get", "some nachos") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment