Created
February 8, 2017 22:28
-
-
Save adamchalmers/350568941e8560957acb5f15bf76f18b to your computer and use it in GitHub Desktop.
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
import Foundation | |
// Represents a calculation that could either succeed, or fail with an error message. | |
enum Result<A> { | |
// If the calculation was successful, store the result. | |
case Ok(A) | |
// If the calculation failed, store the error message. | |
case Err(String) | |
// Chain together two results that could fail. | |
func andThen<B>(f: (_: (A) -> Result<B>)) -> Result<B> { | |
switch self { | |
case .Ok(let val): | |
return f(val) | |
case .Err(let err): | |
return Result<B>.Err(err) | |
} | |
} | |
// Apply a function to an Ok result and ignore errors. | |
func map<B>(f: (A) -> B) -> Result<B> { | |
switch self { | |
case .Ok(let val): | |
return Result<B>.Ok(f(val)) | |
case .Err(let err): | |
return Result<B>.Err(err) | |
} | |
} | |
// Forces unpacking of a Result. | |
func withDefault(def: A) -> A { | |
switch self { | |
case .Ok(let val): | |
return val | |
case .Err: | |
return def | |
} | |
} | |
} | |
//let aged = Either<Int>.Ok(1) | |
let aged = Result<Int>.Err("couldn't get age") | |
let agedMore = aged.andThen(f: {(a: Int) -> Result<Double> in Result.Ok(Double(a)+0.5)}) | |
let ageStr = agedMore.andThen(f: {(a: Double) -> Result<String> in Result.Ok(String(a))}) | |
print(ageStr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment