Skip to content

Instantly share code, notes, and snippets.

@soujiro32167
Created October 3, 2022 13:33
Show Gist options
  • Save soujiro32167/5c3109b5b271d034362e636d071869fc to your computer and use it in GitHub Desktop.
Save soujiro32167/5c3109b5b271d034362e636d071869fc to your computer and use it in GitHub Desktop.
Composing effects with union types
trait F[+A]{
def ++[B >: A](that: F[B]): F[B]
def flatMap[B >: A](f: A => F[B]): F[B]
def map[B](f: A => B): F[B]
}
trait A
trait B
trait C
def a: F[A] = ???
def b: F[B] = ???
def c: F[C] = ???
def empty: F[Nothing] = ???
def compose1: F[A | B] = a ++ b
def composeWithEmpty: F[A | B] = empty ++ compose1
def composeWithEmpty2: F[A | B] = a ++ empty
// def compose2: F[A | B] = a ++ b ++ compose1 // nope - precedence if operators!
def compose3: F[A | B | C] = a ++ (b ++ compose1 ++ c)
def flatMap: F[A | B] = a.flatMap(_ => b)
def flatMapCompose: F[A | B | C] = a.flatMap(_ => compose3)
def program: F[A | B | C] =
for {
_ <- compose3
_ <- a
_ <- b
r <- compose1
} yield r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment