Skip to content

Bowling

Score a game of ten-pin bowling roll by roll, refusing rolls the rules do not allow and a score before the game is over.

Adapted from Exercism’s problem specification (MIT). Listed under Games & Simulation.

// FILE: bowling.nomi
//# Scores a game of ten-pin bowling, roll by roll.

/// A game of bowling: the rolls so far, each one valid when it was rolled.
pub struct Game
    rolls: List<Int>
end

/// Why a roll or a score is refused.
pub enum Error
    NegativeRoll
    TooManyPins
    GameOver
    GameNotOver
end

impl Game
    /// A game with no rolls yet.
    pub fn new() -> Game
        {rolls: []}
    end

    /// The game after a roll that knocks down `pins`.
    pub fn roll(game: Game, pins: Int) -> Result<Game, Error>
        if pins < 0 then return Err(.NegativeRoll)

        Some(standing) = pins_standing(game.rolls, frame: 1) else return Err(.GameOver)
        if pins > standing then return Err(.TooManyPins)
        Ok({rolls: [..game.rolls, pins]})
    end

    /// The total score of a finished game.
    pub fn score(game: Game) -> Result<Int, Error>
        case pins_standing(game.rolls, frame: 1)
            Some(_) -> Err(.GameNotOver)
            None    -> Ok(total(game.rolls, frame: 1))
        end
    end
end

/// The pins standing for the next roll after `rolls`, which start at
/// `frame`, or `None` when the game is over.
fn pins_standing(rolls: List<Int>, frame: Int) -> Maybe<Int>
    case rolls
        _ when frame == 10 -> last_frame_standing(rolls)
        []                 -> Some(10)
        [10, ..rest]       -> pins_standing(rest, frame: frame + 1)
        [first]            -> Some(10 - first)
        [_, _, ..rest]     -> pins_standing(rest, frame: frame + 1)
    end
end

/// The pins standing in the tenth frame after `rolls`. A strike or a spare
/// earns fill balls, and the pins are set up again after each strike and
/// after the spare.
fn last_frame_standing(rolls: List<Int>) -> Maybe<Int>
    case rolls
        [] or [10] or [10, 10] -> Some(10)
        [10, second]           -> Some(10 - second)
        [first]                -> Some(10 - first)
        [first, second] when first + second == 10 -> Some(10)
        _ -> None
    end
end

/// The score of the finished frames `rolls` holds, which start at `frame`.
/// A strike adds the next two rolls and a spare the next one; the tenth
/// frame is its pins, fill balls included.
fn total(rolls: List<Int>, frame: Int) -> Int
    case rolls
        _ when frame == 10 ->
            Iter.sum(rolls)

        [10, ..rest] ->
            10 + bonus(rest, 2) + total(rest, frame: frame + 1)

        [first, second, ..rest] when first + second == 10 ->
            10 + bonus(rest, 1) + total(rest, frame: frame + 1)

        [first, second, ..rest] ->
            first + second + total(rest, frame: frame + 1)

        _ ->
            unreachable "a finished game has two rolls in every frame that is not a strike"
    end
end

/// The pins of the next `count` rolls.
fn bonus(rolls: List<Int>, count: Int) -> Int
    rolls |> Iter.take(count) |> Iter.sum()
end

// FILE: bowling_test.nomi
import bowling.{Error, Game}

/// The game after `rolls`, each of which must succeed.
fn play(rolls: List<Int>) -> Result<Game, Error>
    Iter.try_reduce(rolls, Game.new(), Game.roll)
end

test "score"
    [
        (
            "should be able to score a game with all zeros",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            Ok(0),
        ),
        (
            "should be able to score a game with no strikes or spares",
            [3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6],
            Ok(90),
        ),
        (
            "a spare followed by zeros is worth ten points",
            [6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            Ok(10),
        ),
        (
            "points scored in the roll after a spare are counted twice",
            [6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            Ok(16),
        ),
        (
            "consecutive spares each get a one roll bonus",
            [5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            Ok(31),
        ),
        (
            "a spare in the last frame gets a one roll bonus that is counted once",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7],
            Ok(17),
        ),
        (
            "a strike earns ten points in a frame with a single roll",
            [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            Ok(10),
        ),
        (
            "points scored in the two rolls after a strike are counted twice as a bonus",
            [10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            Ok(26),
        ),
        (
            "consecutive strikes each get the two roll bonus",
            [10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            Ok(81),
        ),
        (
            "a strike in the last frame gets a two roll bonus that is counted once",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1],
            Ok(18),
        ),
        (
            "rolling a spare with the two roll bonus does not get a bonus roll",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3],
            Ok(20),
        ),
        (
            "strikes with the two roll bonus do not get bonus rolls",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10],
            Ok(30),
        ),
        (
            "last two strikes followed by only last bonus with non strike points",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 0, 1],
            Ok(31),
        ),
        (
            "a strike with the one roll bonus after a spare in the last frame does not get a bonus",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10],
            Ok(20),
        ),
        (
            "all strikes is a perfect game",
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            Ok(300),
        ),
        (
            "two bonus rolls after a strike in the last frame can score more than 10 points if one is a strike",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6],
            Ok(26),
        ),
        ("an unstarted game cannot be scored",  [],     Err(Error.GameNotOver)),
        ("an incomplete game cannot be scored", [0, 0], Err(.GameNotOver)),
        (
            "bonus rolls for a strike in the last frame must be rolled before score can be calculated",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10],
            Err(.GameNotOver),
        ),
        (
            "both bonus rolls for a strike in the last frame must be rolled before score can be calculated",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10],
            Err(.GameNotOver),
        ),
        (
            "bonus roll for a spare in the last frame must be rolled before score can be calculated",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3],
            Err(.GameNotOver),
        ),
    ]
    |> subtests (description, rolls, expected), description
        assert Ok(game) = play(rolls)
        assert Game.score(game) == expected
    end
end

test "roll"
    [
        ("rolls cannot score negative points",                    [],  -1, Error.NegativeRoll),
        ("a roll cannot score more than 10 points",               [],  11, .TooManyPins),
        ("two rolls in a frame cannot score more than 10 points", [5], 6,  .TooManyPins),
        (
            "bonus roll after a strike in the last frame cannot score more than 10 points",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10],
            11,
            .TooManyPins,
        ),
        (
            "two bonus rolls after a strike in the last frame cannot score more than 10 points",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5],
            6,
            .TooManyPins,
        ),
        (
            "the second bonus rolls after a strike in the last frame cannot be a strike if the first one is not a strike",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6],
            10,
            .TooManyPins,
        ),
        (
            "second bonus roll after a strike in the last frame cannot score more than 10 points",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10],
            11,
            .TooManyPins,
        ),
        (
            "cannot roll if game already has ten frames",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            0,
            .GameOver,
        ),
        (
            "cannot roll after bonus roll for spare",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 2],
            2,
            .GameOver,
        ),
        (
            "cannot roll after bonus rolls for strike",
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 3, 2],
            2,
            .GameOver,
        ),
    ]
    |> subtests (description, previous, pins, expected), description
        assert Ok(game) = play(previous)
        assert Game.roll(game, pins) == Err(expected)
    end
end
  • A game is a value, Game, holding its rolls. Game.roll returns the game after a roll, or an Err, and Game.score the total of a finished game, so the canonical roll and score operations are owner functions in impl Game that return a new game instead of changing one.
  • The game keeps only the rolls. Whether a roll is allowed, and whether the game is over, both come from one walk over them, pins_standing: it skips whole frames with list patterns ([10, ..rest] for a strike, [_, _, ..rest] for two rolls) and returns the pins standing for the next roll, or None once the game is over. A frame counter or a “fill balls left” field kept beside the rolls would be a second record that could disagree with them.
  • The tenth frame has its own function, last_frame_standing, one case over the frame’s rolls: [10, second] leaves 10 - second pins for the last fill ball, and [] or [10] or [10, 10] a full rack.
  • total scores frames the same way, with a strike’s two bonus rolls and a spare’s one read by bonus from the rolls after the frame. Its last arm is unreachable, since score calls it only for a game pins_standing says is over, which has two rolls in every frame that is not a strike.
  • The four canonical error messages are an Error enum. A roll above the pins standing is TooManyPins whether it is over 10 or over what the frame leaves, as the canonical data gives both one message.
  • The canonical data passes every previous roll to roll, expecting each to succeed. The test file’s play folds them with Iter.try_reduce(rolls, Game.new(), Game.roll), which stops at the first refusal and returns it, and each row asserts Ok(game) = play(rolls), so a refused earlier roll fails the row rather than being mistaken for the expected error.
  • The canonical cases are two subtests tables, one per property, named by the description column: 21 score rows, whose expected value is the score or an error, and 10 roll rows, all errors.