Files
2026-10-29 00:12:08 +01:00

63 lines
2.2 KiB
Scala

package snake
/** An operation an IO program can ask the outside world to perform. */
enum Op:
case Draw(shape: Shape)
case RandomSeed
/** What the outside world answers: `Done` for a `Draw`, `Seed(value)` for a `RandomSeed`. */
enum OpResult:
case Done
case Seed(value: Long)
/**
* m07 io: effects as values. An IO is a plain-data description of a program; nothing runs until interpreted.
* - `Pure(a)` done, with a value
* - `Effect(op, k)` perform `op`, then continue with `k(result)`
*/
enum IO[+A]:
case Pure(a: A)
case Effect(op: Op, k: OpResult => IO[A])
def map[B](f: A => B): IO[B] = flatMap(a => IO.Pure(f(a)))
// Pure: apply f now. Effect: keep the op, and extend the continuation so f runs after k.
// Nothing is performed here, we only build a bigger description.
def flatMap[B](f: A => IO[B]): IO[B] = this match
case Pure(a) => f(a)
case Effect(op, k) => Effect(op, result => k(result).flatMap(f))
final case class Traced[A](result: A, ops: List[Op])
object IO:
def pure[A](a: A): IO[A] = Pure(a)
def effect(op: Op): IO[OpResult] = Effect(op, pure)
def sequence(ios: List[IO[Unit]]): IO[Unit] =
ios.foldRight(pure(()))((io, rest) => io.flatMap(_ => rest))
def draw(shape: Shape): IO[Unit] = effect(Op.Draw(shape)).map(_ => ())
// An interpreter that answers a RandomSeed with anything but a Seed is broken; say so loudly.
lazy val randomSeed: IO[Long] = effect(Op.RandomSeed).map {
case OpResult.Seed(value) => value
case OpResult.Done => throw new IllegalStateException("RandomSeed must be answered with a Seed")
}
def drawScene(scene: Scene): IO[Unit] = sequence(scene.map(draw))
// Answer each op with a canned result, collecting the ops as we go. Tail recursion: the compiler turns it
// into a loop, so long programs cannot overflow the stack, and still nothing is mutated.
def trace[A](io: IO[A], seed: Long): Traced[A] =
@annotation.tailrec
def go(io: IO[A], done: List[Op]): Traced[A] = io match
case Pure(a) => Traced(a, done.reverse)
case Effect(op, k) =>
val answer = op match
case Op.RandomSeed => OpResult.Seed(seed)
case Op.Draw(_) => OpResult.Done
go(k(answer), op :: done)
go(io, Nil)