Skip to content

Instantly share code, notes, and snippets.

@yuk1ty
Created December 28, 2019 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuk1ty/32f350f148129e98a2b395f2ed1a24a8 to your computer and use it in GitHub Desktop.
Save yuk1ty/32f350f148129e98a2b395f2ed1a24a8 to your computer and use it in GitHub Desktop.
scratch-io-monad
sealed trait IO[+A] {
import IO._
def map[B](f: A => B): IO[B] = this match {
case Map(original, g, index) if index != 128 =>
Map(original, g.andThen(f), index + 1)
case _ => Map(this, f, 0)
}
def flatMap[B](f: A => IO[B]): IO[B] = FlatMap(this, f)
}
object IO {
def pure[A](a: A): IO[A] = Pure(a)
def apply[A](a: => A): IO[A] = delay(a)
def delay[A](a: => A): IO[A] = Delay(a _)
def raiseError[A](err: Throwable): IO[A] = RaiseError(err)
final case class Pure[+A](a: A) extends IO[A]
final case class Delay[+A](thunk: () => A) extends IO[A]
final case class RaiseError(err: Throwable) extends IO[Nothing]
final case class FlatMap[E, +A](original: IO[E], f: E => IO[A]) extends IO[A]
final case class Map[E, +A](original: IO[E], f: E => A, index: Int)
extends IO[A]
with (E => IO[A])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment