Last active
December 23, 2015 20:49
-
-
Save AndersNS/6691753 to your computer and use it in GitHub Desktop.
An Erlang implementation of the String calculator kata. Regular Expressions are for sissies. http://osherove.com/tdd-kata-1/
This file contains hidden or 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(stringcalc). | |
-export([add/1, test/0]). | |
%% Test methods. | |
%% Returns ok if all is well. | |
test() -> | |
3 = add("1,2"), | |
0 = add(""), | |
1 = add("1"), | |
6 = add("1\n2,3"), | |
3 = add("//;\n1;2"), | |
6 = add("//[*][%]\n1%2*3"), | |
6 = add("//[****]\n1****2****3"), | |
2 = add("2,1001"), | |
ok. | |
%%% Implementation of the add method | |
add([]) -> 0; | |
add(String) -> | |
{Delim, NewString} = extract_delims(String), | |
Numbers = lists:map(fun(X) -> | |
{Int, _} = string:to_integer(X), Int end, | |
string:tokens(NewString, Delim)), | |
sum(Numbers). | |
extract_delims([$/, $/ | Tail]) -> | |
{FirstLine, Numberstring} = lists:splitwith(fun(S) -> S =/= $\n end, Tail), | |
Delims = delimiters(FirstLine), | |
{Delims, string:substr(Numberstring, 2)}; | |
extract_delims(String) -> | |
{",\n", String}. | |
delimiters(FirstLine) -> | |
lists:flatten(string:tokens(FirstLine, "[]")). | |
sum(Numbers) -> | |
sum(Numbers, 0). | |
sum([], Acc) -> Acc; | |
sum([H|_], _) when H < 0 -> throw("Negative number!!"); | |
sum([H|T], Acc) when H > 1000 -> sum(T, Acc); | |
sum([H|T], Acc) -> sum(T, Acc+H). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment