Skip to content

Instantly share code, notes, and snippets.

@morishin
Created March 14, 2017 10:24
Show Gist options
  • Save morishin/f0f0bda913000bd3ff7a55b20adc31d4 to your computer and use it in GitHub Desktop.
Save morishin/f0f0bda913000bd3ff7a55b20adc31d4 to your computer and use it in GitHub Desktop.
import Foundation
protocol EitherProtocol {
associatedtype Left
associatedtype Right
func either<Result>(ifLeft: (Left) -> Result, ifRight: (Right) -> Result) -> Result
}
extension EitherProtocol {
var left: Left? {
return either(ifLeft: { Optional.some($0) }, ifRight: { _ in return nil })
}
var right: Right? {
return either(ifLeft: { _ in return nil }, ifRight: { Optional.some($0) })
}
var isLeft: Bool {
return either(ifLeft: { _ in return true }, ifRight: { _ in return false })
}
var isRight: Bool {
return either(ifLeft: { _ in return false }, ifRight: { _ in return true })
}
}
enum Either<T, U>: EitherProtocol {
case left(T)
case right(U)
func either<Result>(ifLeft: (T) -> Result, ifRight: (U) -> Result) -> Result {
switch self {
case let .left(x): return ifLeft(x)
case let .right(x): return ifRight(x)
}
}
}
extension Sequence where Iterator.Element: EitherProtocol {
var lefts: [Iterator.Element.Left] {
return flatMap { $0.left }
}
var rights: [Iterator.Element.Right] {
return flatMap { $0.right }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment