Last active
August 29, 2015 14:16
-
-
Save JadenGeller/49872da24dd8de826eae to your computer and use it in GitHub Desktop.
Swift Attempt Function
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
/* | |
* attempt takes a function that does not accept optional values | |
* and returns a new function that will work as usual with non-optional values | |
* and return nil when passed an optional value | |
*/ | |
func attempt<T,U>(f: T -> U)-> T? -> U? { | |
return { y in | |
if let x = y { | |
return f(x) | |
} | |
else { | |
return nil | |
} | |
} | |
} | |
// Example | |
var arr = [3.2, 2.1, 1.0] | |
let x: Double? = 5.0 // Optional value | |
// tl;dr | |
attempt(arr.append)(x) | |
let y = attempt(sqrt)(x) | |
// | |
// Motivation | |
// | |
// No return value | |
arr.append(x) // Error | |
if let x = x { arr.append(x) } // Annoying | |
if (x != nil) { arr.append(x!) } // Gross | |
attempt(arr.append)(x) // >> Yay! << | |
// Return value | |
let y = sqrt(x) // Error | |
if let x = x { let y = sqrt(x) } // Annoying | |
let y = (x != nil) ? sqrt(x!) : nil // Gross | |
let y = attempt(sqrt)(x) // >> Yay! << | |
// Note that the "annoying" example for 'return value' is especially | |
// horrible because all code that uses y must be within the brackets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment