Created
October 23, 2017 20:10
-
-
Save alexpeachey/6019716d75ab5990545660c4c0858e96 to your computer and use it in GitHub Desktop.
Bowling Scoring with Elixir
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
# Stolen from TJ Stankus, ElixirConf 2017 | |
defmodule Bowling do | |
defstruct rolls: [], score: 0 | |
def new_game, do: %Bowling{} | |
def roll(game = %Bowling{}, pinfall) do | |
rolls = append_pinfall(game.rolls, pinfall) | |
%{ game | rolls: rolls, score: score(rolls) } | |
end | |
def score([10, bonus1, bonus2 | _ = []]) do | |
10 + bonus1 + bonus2 | |
end | |
def score([10, bonus1, bonus2 | tail]) do | |
10 + bonus1 + bonus2 + score([bonus1, bonus2 | tail]) | |
end | |
def score([roll1, roll2, bonus | tail]) when roll1 + roll2 == 10 do | |
10 + bonus + score([bonus | tail]) | |
end | |
def score([roll1, roll2 | tail]) when roll1 + roll2 < 10 do | |
roll1 + roll2 + score(tail) | |
end | |
def score([_|_]), do: 0 | |
def score([]), do: 0 | |
defp append_pinfall(rolls, pinfall) do | |
[ pinfall | Enum.reverse(rolls) ] | |
|> Enum.reverse | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment