Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Last active March 15, 2016 03:19
Show Gist options
  • Save ukitaka/bd60e57af3b4fa0d780a to your computer and use it in GitHub Desktop.
Save ukitaka/bd60e57af3b4fa0d780a to your computer and use it in GitHub Desktop.
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