Skip to content

Instantly share code, notes, and snippets.

@fjpse
Created May 23, 2020 15:43
Show Gist options
  • Save fjpse/430224e1b7c8b0782e1e4eb83153fe75 to your computer and use it in GitHub Desktop.
Save fjpse/430224e1b7c8b0782e1e4eb83153fe75 to your computer and use it in GitHub Desktop.
-module(bill).
-export([
database/0,
bill/0,
print_bill/1
]).
database() -> [
{4719, "Fish Fingers" , 121},
{5643, "Nappies" , 1010},
{3814, "Orange Jelly", 56},
{1111, "Hula Hoops", 21},
{1112, "Hula Hoops (Giant)", 133},
{1234, "Dry Sherry, 1lt", 540}
].
bill() -> [1234,4719,3814,1112,1113,1234].
%%
%% find_item(Number, Database) -> Record
%%
find_item(Item, []) -> {Item, "Unknown Item", 0};
find_item(Item, [{Item, _Description, _Value}=Record | _Records]) -> Record;
find_item(Item, [_Record | Records]) -> find_item(Item, Records).
%%
%% print_bill(Bill) -> ok
%%
print_bill(Bill) ->
print_header(),
Total = print_line(Bill, 0),
print_total(Total).
print_header() ->
io:format("~s~n~n", [string:pad("Erlang Stores", 40, both)]).
print_line([], Total) -> Total;
print_line([Item | Items], Total) ->
{_, Description, Value} = find_item(Item, database()),
io:format("~-30...s~10.2..f~n", [Description, Value/100]),
print_line(Items, Total + Value).
print_total(Total) ->
io:format("~n~-30...s~10.2..f~n", ["Total", Total/100]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment