Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created July 13, 2014 01:51
Show Gist options
  • Save kristopherjohnson/c34190c65eccc27192cd to your computer and use it in GitHub Desktop.
Save kristopherjohnson/c34190c65eccc27192cd to your computer and use it in GitHub Desktop.
Swift: For a function that takes two arguments, return equivalent function with argument order reversed (like Haskell "flip")
// For a function that takes two arguments, return equivalent
// function with argument order reversed.
//
// (Like "flip" in Haskell prelude)
func flip<A, B, T>(f: (A, B) -> T) -> (B, A) -> T {
return { (b: B, a: A) -> T in return f(a, b) }
}
// Examples
func subtract(a: Int, b: Int) -> Int {
return a - b
}
let flippedSubtract = flip(subtract)
let result1 = subtract(10, 3) // 7
let result2 = flippedSubtract(10, 3) // -7
func concat(s1: String, s2: String) -> String {
return s1 + s2
}
let reverseConcat = flip(concat)
let result3 = concat("Hello, ", "world!") // "Hello, world!"
let result4 = reverseConcat("Hello, ", "world!") // "world!Hello, "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment