Reputation: 21740
Given a pseudo-union type in Scala.js, how would I fold it into an Either[A, B]
(or a coproduct)?
Upvotes: 0
Views: 125
Reputation: 74394
If you're looking for a function toEither[A, B](union: A | B): Either[A, B]
you're out of luck. The easiest way to see this is to note that it must work for any choices of A
and B
, so if I specialize them both to Unit
toEither[A, B](union: A | B ): Either[A, B]
toEither (union: Unit | Unit): Either[Unit, Unit]
toEither (union: Unit ): Either[Unit, Unit]
it becomes clear that any such function would need to make an arbitrary choice and thus no such function would really exist. Try this exercise with other types C
and A = B = C
.
Generally, unions types are convenient when you recognize that some Javascript function takes several different types of values and distinguishes them at runtime, but they're also less useful than Either
is.
Generally, a function toUnion[A, B](eit: Either[A, B]): A | B
is doing one thing: "forgetting" whether a value is "Left" or "Right" into the undifferentiated union. With this information destroyed you have fewer options to move forward.
Upvotes: 3