Created
December 9, 2016 07:21
-
-
Save ukitaka/020b9aea12c49cd95cc2ec3b7568f924 to your computer and use it in GitHub Desktop.
Scala 2.11までのEitherっぽいEither(right-biasedでないEither)
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
| enum Either<L, R> { | |
| case left(L) | |
| case right(R) | |
| } | |
| extension Either { | |
| var rightProjection: RightProjection<L, R> { | |
| return RightProjection(either: self) | |
| } | |
| var leftProjection: LeftProjection<L, R> { | |
| return LeftProjection(either: self) | |
| } | |
| } | |
| struct RightProjection<L, R> { | |
| let either: Either<L, R> | |
| init(either: Either<L, R>) { | |
| self.either = either | |
| } | |
| func map<R2>(_ f: (R) -> R2) -> Either<L, R2> { | |
| switch self.either { | |
| case .left(let l): | |
| return .left(l) | |
| case .right(let r): | |
| return .right(f(r)) | |
| } | |
| } | |
| func flatMap<R2>(_ f: (R) -> Either<L, R2>) -> Either<L, R2> { | |
| switch self.either { | |
| case .left(let l): | |
| return .left(l) | |
| case .right(let r): | |
| return f(r) | |
| } | |
| } | |
| } | |
| struct LeftProjection<L, R> { | |
| let either: Either<L, R> | |
| init(either: Either<L, R>) { | |
| self.either = either | |
| } | |
| func map<L2>(_ f: (L) -> L2) -> Either<L2, R> { | |
| switch self.either { | |
| case .left(let l): | |
| return .left(f(l)) | |
| case .right(let r): | |
| return .right(r) | |
| } | |
| } | |
| func flatMap<L2>(_ f: (L) -> Either<L2, R>) -> Either<L2, R> { | |
| switch self.either { | |
| case .left(let l): | |
| return f(l) | |
| case .right(let r): | |
| return .right(r) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment