Skip to content

Split-Second Stopwatch

Build a stopwatch that starts, stops, laps and resets, keeping the current lap’s time and every finished lap’s, and refusing a command its state does not allow.

Adapted from Exercism’s problem specification (MIT). Listed under Dates & Time.

// FILE: split_second_stopwatch.nomi
//# A stopwatch that can be started, stopped, lapped and reset.

import std::duration.Duration

/// What a stopwatch is doing.
pub enum State
    Ready
    Running
    Stopped
end

/// A command the stopwatch's state does not allow.
pub enum Error
    AlreadyRunning
    StopWhenNotRunning
    LapWhenNotRunning
    ResetWhenNotStopped
end

impl Display for Error
    fn to_string(error: Error) -> String
        case error
            .AlreadyRunning      -> "cannot start an already running stopwatch"
            .StopWhenNotRunning  -> "cannot stop a stopwatch that is not running"
            .LapWhenNotRunning   -> "cannot lap a stopwatch that is not running"
            .ResetWhenNotStopped -> "cannot reset a stopwatch that is not stopped"
        end
    end
end

once no_time = Duration.seconds(0)

/// A stopwatch that times laps. It is a value: each command answers the
/// stopwatch after it, and time passes when `advance` says so.
pub opaque struct Stopwatch
    state:   State
    current: Duration
    laps:    List<Duration>
end

impl Stopwatch
    /// A stopwatch in the ready state, with no time and no laps.
    pub fn new() -> Stopwatch
        {state: .Ready, current: no_time, laps: []}
    end

    /// Starts timing from the ready state, or resumes it from the stopped one.
    pub fn start(watch: Stopwatch) -> Result<Stopwatch, Error>
        case watch.state
            .Running           -> Err(.AlreadyRunning)
            .Ready or .Stopped -> Ok({..watch, state: .Running})
        end
    end

    /// Pauses a running stopwatch.
    pub fn stop(watch: Stopwatch) -> Result<Stopwatch, Error>
        case watch.state
            .Running           -> Ok({..watch, state: .Stopped})
            .Ready or .Stopped -> Err(.StopWhenNotRunning)
        end
    end

    /// Ends the current lap of a running stopwatch, adding it to the previous
    /// laps, and starts the next from no time.
    pub fn lap(watch: Stopwatch) -> Result<Stopwatch, Error>
        case watch.state
            .Running           -> Ok({..watch, current: no_time, laps: .. + [watch.current]})
            .Ready or .Stopped -> Err(.LapWhenNotRunning)
        end
    end

    /// Clears a stopped stopwatch back to a new one.
    pub fn reset(watch: Stopwatch) -> Result<Stopwatch, Error>
        case watch.state
            .Stopped           -> Ok(Stopwatch.new())
            .Ready or .Running -> Err(.ResetWhenNotStopped)
        end
    end

    /// The stopwatch after `by` has passed: the current lap grows while it
    /// runs, and nothing changes otherwise.
    pub fn advance(watch: Stopwatch, by: Duration) -> Stopwatch
        case watch.state
            .Running           -> {..watch, current: .. + by}
            .Ready or .Stopped -> watch
        end
    end

    /// What the stopwatch is doing.
    pub fn state(watch: Stopwatch) -> State
        watch.state
    end

    /// The time on the current lap.
    pub fn current_lap(watch: Stopwatch) -> Duration
        watch.current
    end

    /// The times of the finished laps, first first.
    pub fn previous_laps(watch: Stopwatch) -> List<Duration>
        watch.laps
    end

    /// The time on every lap, the current one included.
    pub fn total(watch: Stopwatch) -> Duration
        Iter.sum(watch.laps) + watch.current
    end
end

// FILE: split_second_stopwatch_test.nomi
import
    std::duration.Duration
    split_second_stopwatch.{State, Stopwatch}
end

/// One canonical command and what it should do: a command that is allowed,
/// a command refused with a message, time passing, or a reading of the
/// state, the current lap, the total or the previous laps.
enum Step
    Start
    Stop
    Lap
    Reset
    Refused (Step, String)
    Advance Duration
    IsIn State
    CurrentLap Duration
    Total Duration
    PreviousLaps List<Duration>
end

/// Runs each step on a new stopwatch, in turn, and answers the steps as
/// they happened. A run that does what every step says answers the steps it
/// was given.
fn replay(steps: List<Step>) -> List<Step>
    (_watch, happened) =
        steps
        |> Iter.map_reduce(Stopwatch.new(), fn watch, step ->
            case step
                .Start or .Stop or .Lap or .Reset -> command(watch, step)
                .Refused(tried, _message) -> command(watch, tried)
                .Advance(by) -> (Stopwatch.advance(watch, by), step)
                .IsIn(_) -> (watch, .IsIn(Stopwatch.state(watch)))
                .CurrentLap(_) -> (watch, .CurrentLap(Stopwatch.current_lap(watch)))
                .Total(_) -> (watch, .Total(Stopwatch.total(watch)))
                .PreviousLaps(_) -> (watch, .PreviousLaps(Stopwatch.previous_laps(watch)))
            end
        end)

    happened
end

/// Runs the command `step` names, answering the step and the stopwatch
/// after it, or the refusal and the stopwatch unchanged.
fn command(watch: Stopwatch, step: Step) -> (Stopwatch, Step)
    result = case step
        .Start -> Stopwatch.start(watch)
        .Stop  -> Stopwatch.stop(watch)
        .Lap   -> Stopwatch.lap(watch)
        .Reset -> Stopwatch.reset(watch)
        _      -> unreachable "replay passes only the four commands"
    end

    case result
        Ok(next)   -> (next, step)
        Err(error) -> (watch, .Refused(step, "${error}"))
    end
end

test "split second stopwatch"
    [
        ("new stopwatch starts in ready state",             [Step.IsIn(.Ready)]),
        ("new stopwatch's current lap has no elapsed time", [.CurrentLap(Duration"0s")]),
        ("new stopwatch's total has no elapsed time",       [.Total(Duration"0s")]),
        ("new stopwatch does not have previous laps",       [.PreviousLaps([])]),
        ("start from ready state changes state to running", [.Start, .IsIn(.Running)]),
        ("start does not change previous laps",             [.Start, .PreviousLaps([])]),
        (
            "start initiates time tracking for current lap",
            [.Start, .Advance(Duration"5s"), .CurrentLap(Duration"5s")],
        ),
        (
            "start initiates time tracking for total",
            [.Start, .Advance(Duration"23s"), .Total(Duration"23s")],
        ),
        (
            "start cannot be called from running state",
            [.Start, .Refused(.Start, "cannot start an already running stopwatch")],
        ),
        ("stop from running state changes state to stopped", [.Start, .Stop, .IsIn(.Stopped)]),
        (
            "stop pauses time tracking for current lap",
            [
                .Start,
                .Advance(Duration"5s"),
                .Stop,
                .Advance(Duration"8s"),
                .CurrentLap(Duration"5s"),
            ],
        ),
        (
            "stop pauses time tracking for total",
            [
                .Start,
                .Advance(Duration"13s"),
                .Stop,
                .Advance(Duration"44s"),
                .Total(Duration"13s"),
            ],
        ),
        (
            "stop cannot be called from ready state",
            [.Refused(.Stop, "cannot stop a stopwatch that is not running")],
        ),
        (
            "stop cannot be called from stopped state",
            [.Start, .Stop, .Refused(.Stop, "cannot stop a stopwatch that is not running")],
        ),
        (
            "start from stopped state changes state to running",
            [.Start, .Stop, .Start, .IsIn(.Running)],
        ),
        (
            "start from stopped state resumes time tracking for current lap",
            [
                .Start,
                .Advance(Duration"1m20s"),
                .Stop,
                .Advance(Duration"20s"),
                .Start,
                .Advance(Duration"8s"),
                .CurrentLap(Duration"1m28s"),
            ],
        ),
        (
            "start from stopped state resumes time tracking for total",
            [
                .Start,
                .Advance(Duration"23s"),
                .Stop,
                .Advance(Duration"44s"),
                .Start,
                .Advance(Duration"9s"),
                .Total(Duration"32s"),
            ],
        ),
        (
            "lap adds current lap to previous laps",
            [
                .Start,
                .Advance(Duration"1m38s"),
                .Lap,
                .PreviousLaps([Duration"1m38s"]),
                .Advance(Duration"44s"),
                .Lap,
                .PreviousLaps([Duration"1m38s", Duration"44s"]),
            ],
        ),
        (
            "lap resets current lap and resumes time tracking",
            [
                .Start,
                .Advance(Duration"8m22s"),
                .Lap,
                .CurrentLap(Duration"0s"),
                .Advance(Duration"15s"),
                .CurrentLap(Duration"15s"),
            ],
        ),
        (
            "lap continues time tracking for total",
            [.Start, .Advance(Duration"22s"), .Lap, .Advance(Duration"33s"), .Total(Duration"55s")],
        ),
        (
            "lap cannot be called from ready state",
            [.Refused(.Lap, "cannot lap a stopwatch that is not running")],
        ),
        (
            "lap cannot be called from stopped state",
            [.Start, .Stop, .Refused(.Lap, "cannot lap a stopwatch that is not running")],
        ),
        (
            "stop does not change previous laps",
            [
                .Start,
                .Advance(Duration"11m22s"),
                .Lap,
                .PreviousLaps([Duration"11m22s"]),
                .Stop,
                .PreviousLaps([Duration"11m22s"]),
            ],
        ),
        (
            "reset from stopped state changes state to ready",
            [.Start, .Stop, .Reset, .IsIn(.Ready)],
        ),
        (
            "reset resets current lap",
            [.Start, .Advance(Duration"10s"), .Stop, .Reset, .CurrentLap(Duration"0s")],
        ),
        (
            "reset clears previous laps",
            [
                .Start,
                .Advance(Duration"10s"),
                .Lap,
                .Advance(Duration"20s"),
                .Lap,
                .PreviousLaps([Duration"10s", Duration"20s"]),
                .Stop,
                .Reset,
                .PreviousLaps([]),
            ],
        ),
        (
            "reset cannot be called from ready state",
            [.Refused(.Reset, "cannot reset a stopwatch that is not stopped")],
        ),
        (
            "reset cannot be called from running state",
            [.Start, .Refused(.Reset, "cannot reset a stopwatch that is not stopped")],
        ),
        (
            "supports very long laps",
            [
                .Start,
                .Advance(Duration"1h23m45s"),
                .CurrentLap(Duration"1h23m45s"),
                .Lap,
                .PreviousLaps([Duration"1h23m45s"]),
                .Advance(Duration"4h1m40s"),
                .CurrentLap(Duration"4h1m40s"),
                .Total(Duration"5h25m25s"),
                .Lap,
                .PreviousLaps([Duration"1h23m45s", Duration"4h1m40s"]),
                .Advance(Duration"8h43m5s"),
                .CurrentLap(Duration"8h43m5s"),
                .Total(Duration"14h8m30s"),
                .Lap,
                .PreviousLaps([Duration"1h23m45s", Duration"4h1m40s", Duration"8h43m5s"]),
            ],
        ),
    ]
    |> subtests (description, steps), description
        assert replay(steps) == steps
    end
end
  • Adapted: the exercise asks for a stopwatch object whose commands change it in place while a clock runs. Nomi values do not change, so Stopwatch is a value and each command answers the stopwatch after it, and time passes only when Stopwatch.advance says so, which is what the canonical data’s advanceTime command stands for. No clock is read, so every case is deterministic.
  • Stopwatch is an opaque struct of its State, the current lap’s Duration and the finished laps. start, stop, lap and reset return Result<Stopwatch, Error>, each one case over the state; Error has a variant per refusal and its Display gives the canonical messages. advance adds time only while running, and total is Iter.sum of the laps plus the current one.
  • Times are Durations in the API and in the test file, which writes the canonical HH:MM:SS times as Duration literals: 00:01:28 is Duration"1m28s", and a reading compares as a Duration.
  • Each canonical case is a list of commands and readings, so the test file writes them as Step variants, as circular-buffer does: the four commands, Refused(command, message) for one the state refuses, Advance(time), and the four readings with their expected values. replay runs the steps with Iter.map_reduce from a new stopwatch and answers what happened in the same shape, so each case is one replay(steps) == steps, and a failure shows the first step that went differently. Refused holds the command it tried, so the enum refers to itself.
  • The 29 canonical cases are one subtests table named by the description column.