 # marionebl's solution

## to Bowling in the OCaml Track

Published at Jun 20 2019 · 0 comments
Instructions
Test suite
Solution

#### Note:

This exercise has changed since this solution was written.

Score a bowling game.

Bowling is a game where players roll a heavy ball to knock down pins arranged in a triangle. Write code to keep track of the score of a game of bowling.

## Scoring Bowling

The game consists of 10 frames. A frame is composed of one or two ball throws with 10 pins standing at frame initialization. There are three cases for the tabulation of a frame.

• An open frame is where a score of less than 10 is recorded for the frame. In this case the score for the frame is the number of pins knocked down.

• A spare is where all ten pins are knocked down by the second throw. The total value of a spare is 10 plus the number of pins knocked down in their next throw.

• A strike is where all ten pins are knocked down by the first throw. The total value of a strike is 10 plus the number of pins knocked down in the next two throws. If a strike is immediately followed by a second strike, then the value of the first strike cannot be determined until the ball is thrown one more time.

Here is a three frame example:

Frame 1 Frame 2 Frame 3
X (strike) 5/ (spare) 9 0 (open frame)

Frame 1 is (10 + 5 + 5) = 20

Frame 2 is (5 + 5 + 9) = 19

Frame 3 is (9 + 0) = 9

This means the current running total is 48.

The tenth frame in the game is a special case. If someone throws a strike or a spare then they get a fill ball. Fill balls exist to calculate the total of the 10th frame. Scoring a strike or spare on the fill ball does not give the player more fill balls. The total value of the 10th frame is the total number of pins knocked down.

For a tenth frame of X1/ (strike and a spare), the total value is 20.

For a tenth frame of XXX (three strikes), the total value is 30.

## Requirements

Write code to keep track of the score of a game of bowling. It should support two operations:

• `roll(pins : int)` is called each time the player rolls a ball. The argument is the number of pins knocked down.
• `score() : int` is called only at the very end of the game. It returns the total score for that game.

## Getting Started

For installation and learning resources, refer to the exercism help page.

## Installation

To work on the exercises, you will need `Opam` and `Base`. Consult opam website for instructions on how to install `opam` for your OS. Once `opam` is installed open a terminal window and run the following command to install base:

``````opam install base
``````

To run the tests you will need `OUnit`. Install it using `opam`:

``````opam install ounit
``````

## Running Tests

A Makefile is provided with a default target to compile your solution and run the tests. At the command line, type:

``````make
``````

## Interactive Shell

`utop` is a command line program which allows you to run Ocaml code interactively. The easiest way to install it is via opam:

``````opam install utop
``````

Consult utop for more detail.

## Feedback, Issues, Pull Requests

The exercism/ocaml repository on GitHub is the home for all of the Ocaml exercises.

If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue. We'll do our best to help you!

## Source

The Bowling Game Kata at but UncleBob http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### test.ml

``````open Base
open OUnit2
open Bowling

type game = Bowling.t

let to_ok = function
| Ok x -> x
| Error e -> failwith @@ "should be OK but got Error " ^ e

let set_previous_frames (frames : int list): game =
List.fold frames ~init:new_game ~f:(fun g f -> roll f g |> to_ok)

let score_printer = function
| Ok n -> Int.to_string n
| Error e -> e
let assert_score exp game = assert_equal ~printer:score_printer exp (score game)

let roll_printer = function
| Ok _ -> "Ok <some game>"
| Error e -> e
let assert_roll exp frame game = assert_equal ~printer:roll_printer exp (roll frame game)

let tests = [
"should be able to score a game with all zeros" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_score (Ok 0) g
);
"should be able to score a game with no strikes or spares" >:: (fun _ ->
let g = set_previous_frames [3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6] in
assert_score (Ok 90) g
);
"a spare followed by zeros is worth ten points" >:: (fun _ ->
let g = set_previous_frames [6; 4; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_score (Ok 10) g
);
"points scored in the roll after a spare are counted twice" >:: (fun _ ->
let g = set_previous_frames [6; 4; 3; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_score (Ok 16) g
);
"consecutive spares each get a one roll bonus" >:: (fun _ ->
let g = set_previous_frames [5; 5; 3; 7; 4; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_score (Ok 31) g
);
"a spare in the last frame gets a one roll bonus that is counted once" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 7; 3; 7] in
assert_score (Ok 17) g
);
"a strike earns ten points in a frame with a single roll" >:: (fun _ ->
let g = set_previous_frames [10; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_score (Ok 10) g
);
"points scored in the two rolls after a strike are counted twice as a bonus" >:: (fun _ ->
let g = set_previous_frames [10; 5; 3; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_score (Ok 26) g
);
"consecutive strikes each get the two roll bonus" >:: (fun _ ->
let g = set_previous_frames [10; 10; 10; 5; 3; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_score (Ok 81) g
);
"a strike in the last frame gets a two roll bonus that is counted once" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 7; 1] in
assert_score (Ok 18) g
);
"rolling a spare with the two roll bonus does not get a bonus roll" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 7; 3] in
assert_score (Ok 20) g
);
"strikes with the two roll bonus do not get bonus rolls" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10; 10] in
assert_score (Ok 30) g
);
"a strike with the one roll bonus after a spare in the last frame does not get a bonus" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 7; 3; 10] in
assert_score (Ok 20) g
);
"all strikes is a perfect game" >:: (fun _ ->
let g = set_previous_frames [10; 10; 10; 10; 10; 10; 10; 10; 10; 10; 10; 10] in
assert_score (Ok 300) g
);
"rolls cannot score negative points" >:: (fun _ ->
let g = set_previous_frames [] in
assert_roll (Error "Negative roll is invalid") (-1) g
);
"a roll cannot score more than 10 points" >:: (fun _ ->
let g = set_previous_frames [] in
assert_roll (Error "Pin count exceeds pins on the lane") 11 g
);
"two rolls in a frame cannot score more than 10 points" >:: (fun _ ->
let g = set_previous_frames  in
assert_roll (Error "Pin count exceeds pins on the lane") 6 g
);
"bonus roll after a strike in the last frame cannot score more than 10 points" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10] in
assert_roll (Error "Pin count exceeds pins on the lane") 11 g
);
"two bonus rolls after a strike in the last frame cannot score more than 10 points" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 5] in
assert_roll (Error "Pin count exceeds pins on the lane") 6 g
);
"two bonus rolls after a strike in the last frame can score more than 10 points if one is a strike" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10; 6] in
assert_score (Ok 26) g
);
"the second bonus rolls after a strike in the last frame cannot be a strike if the first one is not a strike" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 6] in
assert_roll (Error "Pin count exceeds pins on the lane") 10 g
);
"second bonus roll after a strike in the last frame cannot score more than 10 points" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10] in
assert_roll (Error "Pin count exceeds pins on the lane") 11 g
);
"an unstarted game cannot be scored" >:: (fun _ ->
let g = set_previous_frames [] in
assert_score (Error "Score cannot be taken until the end of the game") g
);
"an incomplete game cannot be scored" >:: (fun _ ->
let g = set_previous_frames [0; 0] in
assert_score (Error "Score cannot be taken until the end of the game") g
);
"cannot roll if game already has ten frames" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
assert_roll (Error "Cannot roll after game is over") 0 g
);
"bonus rolls for a strike in the last frame must be rolled before score can be calculated" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10] in
assert_score (Error "Score cannot be taken until the end of the game") g
);
"both bonus rolls for a strike in the last frame must be rolled before score can be calculated" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10] in
assert_score (Error "Score cannot be taken until the end of the game") g
);
"bonus roll for a spare in the last frame must be rolled before score can be calculated" >:: (fun _ ->
let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 7; 3] in
assert_score (Error "Score cannot be taken until the end of the game") g
);
]

let () =
run_test_tt_main ("bowling tests" >::: tests)``````

### bowling.ml

``````open Base
open Game

type t = Game.t

let new_game = Game.empty

let roll (knocked: int) (game: Game.t): (Game.t, string) Result.t =
match Game.progress game knocked with
| Ok { phase=Game.Bonus; _ } -> Game.bonus game knocked
| Ok { roll=Roll.Empty; knocked=10; _ } -> Game.strike game
| Ok { roll=Roll.Pending _; sum=10; _ } -> Game.spare game knocked
| Ok { roll=Roll.Pending _; _ } -> Game.opn game knocked
| Ok { roll=Roll.Empty; _ } -> Game.roll game knocked
| Error m -> Error m

let score = Game.score``````

### frame.ml

``````open Base

type t =
| Open of int * int
| Spare of int * int
| Strike
| Bonus of int

let to_string = function
| Open (f, s) -> Printf.sprintf "Frame.Open (%i, %i)" f s
| Spare (f, s) -> Printf.sprintf "Frame.Spare (%i, %i)" f s
| Strike -> "Frame.Strike"
| Bonus b ->  Printf.sprintf "Frame.Bonus %i" b

let value = function
| Open (f, s) | Spare (f, s) -> f + s
| Strike -> 10
| Bonus b -> b

let extend (frames: t list) (index: int) (n: int) =
let rec extend' rolls index n =
if Int.(n = 0) then
rolls
else
match List.nth frames (index + 1) with
| Some Open (f, s) | Some Spare (f, s) ->
let r = List.take [f; s] n in
extend' (rolls @ r) (index + 1) (n - List.length r)
| Some Strike -> extend' (rolls @ ) (index + 1) (n - 1)
| Some Bonus b -> extend' (rolls @ [b]) (index + 1) (n - 1)
| None -> rolls
in
extend' [] index n |> List.fold ~init:0 ~f:(+)

let score (frames: t list) (index: int) (frame: t) =
value frame + match frame with
| _ when Int.(=) 10 (index + 1) -> 0
| Strike -> extend frames index 2
| Spare _ -> extend frames index 1
| Open _ | Bonus _ -> 0``````

### game.ml

``````open Base

type p = Game | Bonus | Done
type t = { roll: Roll.t; frames: Frame.t list; phase: p }
type transition = { roll: Roll.t; knocked: int; sum: int; phase: p }

let empty = { roll=Roll.Empty; frames=[]; phase=Game }

let phase (game: t): p =
match (List.nth game.frames 9, List.length game.frames) with
| (None, _) -> Game
| (Some Frame.Strike, 12) -> Done
| (Some Frame.Strike, _) -> Bonus
| (Some Frame.Spare _, 11) -> Done
| (Some Frame.Spare _, _) -> Bonus
| _ -> Done

let progress (game: t) (knocked: int): (transition, string) Result.t =
if phys_equal game.phase Done then
Error "Cannot roll after game is over"
else
Roll.sum game.roll knocked
|> Result.map ~f:(fun sum -> { roll=game.roll; knocked=knocked; sum=sum; phase=(phase game) })

let add_frame (game: t) (frame: Frame.t): t =
let next = { roll=Roll.Empty; frames=game.frames @ [frame]; phase=Game } in
{ roll=next.roll; frames=next.frames; phase=phase next }

let last_frame (game: t): Frame.t option =
List.last game.frames

let strike (game: t): (t, string) Result.t =

let spare (game: t) (k: int): (t, string) Result.t =
match game with
| { roll=Roll.Pending p; _ } -> Ok (add_frame game (Frame.Spare (p, k)))
| _ -> Error "no-spare-possible"

let opn (game: t) (k: int): (t, string) Result.t =
match game with
| { roll=Roll.Pending p; _ } -> Ok (add_frame game (Frame.Open (p, k)))
| _ -> Error "no-spare-possible"

let bonus (game: t) (k: int): (t, string) Result.t =
match (game, last_frame game) with
| (_, Some Frame.Bonus pk) when pk <> 10 && pk + k > 10 -> Error "Pin count exceeds pins on the lane"
| ({ roll=Roll.Empty; _ }, _) -> Ok (add_frame game (Frame.Bonus k))
| _ -> Error "no-bonus-possible"

let roll (game: t) (k: int): (t, string) Result.t =
Ok { roll=Roll.Pending k; frames=game.frames; phase=Game }

let to_string (game: t) =
Printf.sprintf "{ roll=%s; frames=[%s]; }"
(Roll.to_string game.roll)
(List.map game.frames ~f:Frame.to_string |> String.concat ~sep:"; ")

let score (game: t): (int, string) Result.t =
if phys_equal game.phase Done then
game.frames
|> List.mapi ~f:(Frame.score game.frames)
|> List.fold ~init:0 ~f:(+)
|> Result.return
else
Error "Score cannot be taken until the end of the game"``````

### roll.ml

``````open Base

type t =
| Empty
| Pending of int

let value = function
| Empty -> 0
| Pending v -> v

let sum (r: t) (n: int): (int, string) Result.t =
if n < 0 then
Error "Negative roll is invalid"
else if value r + n > 10 then
Error "Pin count exceeds pins on the lane"
else
Ok (value r + n)

let to_string = function
| Empty -> "Roll.Empty"
| Pending p -> Printf.sprintf "Roll.Pending %i" p``````