Skip to content

Instantly share code, notes, and snippets.

@joelreymont
Created July 30, 2011 16:15
Show Gist options
  • Save joelreymont/1115688 to your computer and use it in GitHub Desktop.
Save joelreymont/1115688 to your computer and use it in GitHub Desktop.
Simple calculator kata in Erlang
-module(calc).
-export([calc/1]).
-include_lib("eunit/include/eunit.hrl").
calc(<<"">>) ->
0;
calc(Input)
when is_binary(Input) ->
calc(Input, []).
calc(<<N, Rest/binary>>, ParsedNumbers)
when N >= $0, N =< $9 ->
calc(Rest, [N - $0|ParsedNumbers]);
calc(<<_Sep, Rest/binary>>, ParsedNumbers) ->
calc(Rest, ParsedNumbers);
calc(<<"">>, ParsedNumbers) ->
lists:foldl(fun(N, Acc) -> Acc + N end, 0, ParsedNumbers).
integer_to_binary(N)
when is_integer(N) ->
list_to_binary(integer_to_list(N)).
%%%
%%% Test suite
%%%
empty_string_test() ->
?assertEqual(0, calc(<<"">>)).
single_number_test() ->
?assertEqual(9, calc(<<"9">>)).
random_number_test() ->
N = random:uniform(9),
Bin = integer_to_binary(N),
?assertEqual(N, calc(Bin)).
two_number_test() ->
?assertEqual(3, calc(<<"1 2">>)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment