Created
October 3, 2022 13:31
-
-
Save soujiro32167/0f146108099b6fea24dfd9139a64a6d8 to your computer and use it in GitHub Desktop.
Flattening an Either tree in Scala 3
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
import scala.annotation.tailrec | |
type FlatEither[A] = A match | |
case Either[l, r] => FlatEither[l] | FlatEither[r] | |
case _ => A | |
@tailrec | |
def flatEither[A](a: A): FlatEither[A] = a match | |
case e: Either[?, ?] => e match | |
case Right(r) => flatEither(r) | |
case Left(l) => flatEither(l) | |
case _ => a | |
val flatSimple: Int | String = flatEither(Right(1).withLeft[String]) | |
assert(flatSimple == 1) | |
val e: Either[Either[Boolean, String], Int] = Left(Right("string")) | |
val flat: Boolean | String | Int = flatEither(e) | |
assert(flat == "string") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment