Skip to content

Instantly share code, notes, and snippets.

@hohonuuli
Last active November 19, 2024 19:40
Show Gist options
  • Save hohonuuli/796730cc1069cb0c5d1ad0dd5a4493f1 to your computer and use it in GitHub Desktop.
Save hohonuuli/796730cc1069cb0c5d1ad0dd5a4493f1 to your computer and use it in GitHub Desktop.
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