Skip to content

Instantly share code, notes, and snippets.

@bluegraybox
Created August 2, 2011 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluegraybox/1119461 to your computer and use it in GitHub Desktop.
Save bluegraybox/1119461 to your computer and use it in GitHub Desktop.
Code for scoring a bowling game.
-module(game).
-export([score/1]).
score(Rolls) -> frame(1, 0, Rolls).
%% frame/3 takes Frame #, Score accumulator, and list of remaining Rolls.
%% It tail-recurses to the next frame with an updated Score and Rolls list.
%% Game complete.
frame(11, Score, _BonusRolls) -> Score;
%% Strike.
frame(Frame, Score, [10|Rest]) ->
[Bonus1, Bonus2|_] = Rest,
frame(Frame + 1, Score + 10 + Bonus1 + Bonus2, Rest);
%% Bad input.
frame(_Frame, _Score, [First,Second|_Rest]) when (First + Second > 10) -> err;
%% Spare.
frame(Frame, Score, [First,Second|Rest]) when (First + Second == 10) ->
[Bonus1|_] = Rest,
frame(Frame + 1, Score + 10 + Bonus1, Rest);
%% Normal.
frame(Frame, Score, [First,Second|Rest]) ->
frame(Frame + 1, Score + First + Second, Rest).
@bluegraybox
Copy link
Author

This is the original version, with almost no error checking. It barfs on incomplete games. The latest version with full error handling is at https://github.com/bluegraybox/examples/blob/master/bowling/erlang/game.erl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment