Skip to content

Instantly share code, notes, and snippets.

@JRHeaton
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save JRHeaton/9ce132b285f3edd21e97 to your computer and use it in GitHub Desktop.

Select an option

Save JRHeaton/9ce132b285f3edd21e97 to your computer and use it in GitHub Desktop.
Composing/partially applying unary/binary functions
// binary currying
func curry<T, U, V>(f: (T, U) -> V) -> T -> U -> V {
return { x in { y in f(x, y) }}
}
// binary uncurry
func uncurry<T, U, V>(f: T -> U -> V) -> (T, U) -> V {
return { f($0)($1) }
}
// compose operator (left to right)
infix operator ~> { associativity left }
// unary composition
func ~> <T, U, V>(f: T -> U, g: U -> V) -> T -> V {
return { g(f($0)) }
}
// binary (uncurried) to unary composition
func ~> <T, U, V, W>(f: (T, U) -> V, g: V -> W) -> (T, U) -> W {
return curry(f) ~> g
}
// binary (curried) to unary composition
func ~> <T, U, V, W>(f: T -> U -> V, g: V -> W) -> (T, U) -> W {
return uncurry { f($0) ~> g }
}
// new function w/ reverse order ("flip")
prefix func ~ <T, U, V> (f: (T, U) -> V) -> (U, T) -> V {
return { f($1, $0) }
}
let p2t2 = curry(+)(2) ~> { $0 * 2 }
// option 1: reverse order args to top level map
let algorithm: [Int] -> [Int]
= reverse ~> curry(~map)(p2t2)
// option 2: inline closure delegating to map member function
let a2: [Int] -> [Int]
= reverse ~> { $0.map(p2t2) }
let a = algorithm([2, 4, 6, 8, 10])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment