Created
December 28, 2019 13:14
-
-
Save yuk1ty/32f350f148129e98a2b395f2ed1a24a8 to your computer and use it in GitHub Desktop.
scratch-io-monad
This file contains 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
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