Last active
March 15, 2016 03:19
-
-
Save ukitaka/bd60e57af3b4fa0d780a to your computer and use it in GitHub Desktop.
This file contains 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
struct PartialFunction<A, B> { | |
let f: A throws -> B | |
init(_ f: A throws -> B) { | |
self.f = f | |
} | |
} | |
extension Optional { | |
func collect<B>(f: PartialFunction<Wrapped, B>) -> Optional<B> { | |
if let res = try? self.map(f.f) { | |
return res | |
} else { | |
return .None | |
} | |
} | |
} | |
enum PartialFunctionError: ErrorType { | |
case MatchErorr | |
} | |
let f = PartialFunction<Int, String> { a in | |
switch a { | |
case 1: | |
return "hello!!" | |
default: | |
throw PartialFunctionError.MatchErorr | |
} | |
} | |
Optional<Int>(1).collect(f) // hello! | |
Optional<Int>(2).collect(f) // nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment