57 lines
2.6 KiB
FSharp
57 lines
2.6 KiB
FSharp
/// m07 io: effects as values. An `IO<'a>` is a description of a program that, when interpreted, produces an `'a`:
|
|
/// - `Pure a` finished, nothing left to do
|
|
/// - `Effect (op, k)` perform `op`, then continue with `k result` (which returns another IO)
|
|
/// Building an IO never performs anything; only an interpreter (`trace` here, `Runtime.runIO` in m09) does.
|
|
module Snake.IO
|
|
|
|
open Snake.View
|
|
|
|
/// An operation an IO program can ask the outside world to perform.
|
|
type Op =
|
|
| Draw of Shape
|
|
| RandomSeed
|
|
|
|
/// What the outside world answers: `Done` for a `Draw`, `Seed value` (an unsigned 32-bit number) for a `RandomSeed`.
|
|
type OpResult =
|
|
| Done
|
|
| Seed of uint32
|
|
|
|
type IO<'a> =
|
|
| Pure of 'a
|
|
| Effect of Op * (OpResult -> IO<'a>)
|
|
|
|
/// The result of `trace`: the final value and the operations performed, in execution order.
|
|
type Traced<'a> = { Result: 'a; Ops: Op list }
|
|
|
|
/// An IO that does nothing and produces `a`.
|
|
let pure (a: 'a) : IO<'a> = failwith "TODO m07"
|
|
|
|
/// An IO that performs the single operation `op` and produces its result: `Effect (op, pure)`.
|
|
let effect (op: Op) : IO<OpResult> = failwith "TODO m07"
|
|
|
|
/// Run `io`, then feed its result to `f` to get the next IO.
|
|
/// `Pure a`: `f a`. `Effect (op, k)`: the same op, with the continuation extended by `f`.
|
|
let bind (f: 'a -> IO<'b>) (io: IO<'a>) : IO<'b> = failwith "TODO m07"
|
|
|
|
/// Transform the result with `f`. Must not call `f` until the IO is interpreted.
|
|
let map (f: 'a -> 'b) (io: IO<'a>) : IO<'b> = failwith "TODO m07"
|
|
|
|
/// Run the IOs one after another, left to right, producing `()`. `sequence []` performs nothing.
|
|
let sequence (ios: IO<unit> list) : IO<unit> = failwith "TODO m07"
|
|
|
|
/// An IO that draws one shape (a `Rect` or `Text` from m06) and produces `()`.
|
|
let draw (shape: Shape) : IO<unit> = failwith "TODO m07"
|
|
|
|
/// An IO that asks the outside world for a random seed and produces it (the `value` of the `Seed` answer).
|
|
/// It is a function of `unit` (use it as `randomSeed ()`) because F# evaluates module-level values as soon as
|
|
/// the module is used; every call returns the same description.
|
|
let randomSeed () : IO<uint32> = failwith "TODO m07"
|
|
|
|
/// Draw every shape of a scene in order: `sequence (List.map draw scene)`.
|
|
let drawScene (scene: Scene) : IO<unit> = failwith "TODO m07"
|
|
|
|
/// A pure interpreter for tests. Answers every `RandomSeed` with `Seed seed` and every `Draw` with `Done`.
|
|
/// Returns the final value and the operations in the order they were executed.
|
|
/// Implemented by recursion, with no mutation.
|
|
let trace (seed: uint32) (io: IO<'a>) : Traced<'a> = failwith "TODO m07"
|