Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Created September 16, 2019 03:05
Show Gist options
  • Save Koshimizu-Takehito/556e1b5a7b2138a0eaa4f8f36b0fed80 to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/556e1b5a7b2138a0eaa4f8f36b0fed80 to your computer and use it in GitHub Desktop.
public protocol EitherProtocol {
associatedtype Left
associatedtype Right
var either: Either<Left, Right> { get }
}
public enum Either<Left, Right> {
case left(Left)
case right(Right)
}
extension Either: EitherProtocol {
public var either: Either<Left, Right> {
return self
}
}
extension Either: Equatable where Left: Equatable, Right: Equatable {
}
extension Either: Hashable where Left: Hashable, Right: Hashable {
}
public extension Either {
func mapLeft<Left2>(_ transform: (Left) -> Left2) -> Either<Left2, Right> {
switch self {
case let .left(value):
return .left(transform(value))
case let .right(value):
return .right(value)
}
}
func mapRight<Right2>(_ transform: (Right) -> Right2) -> Either<Left, Right2> {
switch self {
case let .left(value):
return .left(value)
case let .right(value):
return .right(transform(value))
}
}
func flatMapLeft<Left2>(_ transform: (Left) -> Either<Left2, Right>) -> Either<Left2, Right> {
switch self {
case let .left(value):
return transform(value)
case let .right(value):
return .right(value)
}
}
func flatMapRight<Right2>(_ transform: (Right) -> Either<Left, Right2>) -> Either<Left, Right2> {
switch self {
case let .left(value):
return .left(value)
case let .right(value):
return transform(value)
}
}
}
public extension Either where Left == Never {
var right: Right {
switch self {
case let .right(value):
return value
}
}
}
public extension Either where Right == Never {
var left: Left {
switch self {
case let .left(value):
return value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment