Last active
November 19, 2024 19:40
-
-
Save hohonuuli/796730cc1069cb0c5d1ad0dd5a4493f1 to your computer and use it in GitHub Desktop.
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.concurrent.{ExecutionContext, Future} | |
/** | |
* Poor-man's IO | |
*/ | |
type IO[A, B] = A => Either[Throwable, B] | |
type AsyncIO[A, B] = A => Future[B] | |
object IO: | |
extension [A, B](io: IO[A, B]) | |
def unit: IO[A, Unit] = a => Right(()) | |
def flatMap[C](f: IO[B, C]): IO[A, C] = a => io(a).flatMap(b => f(b)) | |
def map[C](f: B => C): IO[A, C] = a => io(a).map(f) | |
def foreach(f: B => Unit): IO[A, Unit] = a => | |
for b <- io(a) | |
yield f(b) | |
def async(using executionContext: ExecutionContext): AsyncIO[A, B] = a => | |
Future(io(a)).map { | |
case Right(b) => b | |
case Left(e) => throw e | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment