feat(scala): m07 io and m08 stream with tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
56bc6b4cf7
commit
bd0c9fcc0c
@@ -0,0 +1,62 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user