Created
August 2, 2011 02:20
-
-
Save bluegraybox/1119461 to your computer and use it in GitHub Desktop.
Code for scoring a bowling game.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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