Created
July 13, 2014 01:51
-
-
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")
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
// 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