view 5-Erlang/day1.erl @ 71:32f018861e36

Add Day 1 Erlang content
author IBBoard <dev@ibboard.co.uk>
date Fri, 02 Feb 2018 20:38:36 +0000
parents
children
line wrap: on
line source

-module(day1).
-export([wordcount/1]).
-export([count_to_ten/0]).
-export([success_or_error/1]).

wordcount("") -> 0;
wordcount([_|[]]) -> 1;
% NOTE: We can't use " " here - because it is a string and hence an array, not a character.
% Instead we get a slightly ugly "dollar space"
% Note the funky extra match to handle multiple consecutive spaces (although we still don't handle leading or trailing spaces)
wordcount([$ |[$ |Tail]]) -> wordcount([$ |Tail]);
wordcount([$ |Tail]) -> 1 + wordcount(Tail);
wordcount([_|Tail]) -> wordcount(Tail).

count_to(1) -> io:fwrite("~B ", [1]);
count_to(N) -> count_to(N-1), io:fwrite("~B ", [N]).

count_to_ten() -> count_to(10), io:fwrite("~n").

success_or_error({error, Message}) -> io:fwrite("error: ~s~n", [Message]);
success_or_error(success) -> io:fwrite("success~n").