Yesterday’s stab at “my first erlang sample” – which I want to, again, emphasize is a matter of exercise and not a demonstration of The Right Way to achieve the stated goal – didn’t make use of tail recursion. I’ve also picked up a few more bits of Erlang (thanks to “Learn you some Erlang for great good“), and my new version is this:
% Count the words in an array. % ASSUMPTION: Array contains only letters and spaces. -module(test). % Only export the version that takes just the list. -export([word_count/1]). % This is our entry point function which starts the % recursive loop with a counter of 0. word_count(List) -> word_count(List, 0). % When we reach the end, return the count. word_count([], N) -> N; % Spaces themselves don't count for anything; % this syntax includes testing for trailing spaces. word_count([ 32 | Rest], N) -> word_count(Rest, N); % Catch the case of the last word in the list % not having a space after it. word_count([_], N) -> N + 1; % Something followed by a space is end of word, % because we've already eliminated space|something. word_count([_, 32 | Rest], N) -> word_count(Rest, N + 1); % Otherwise, carry on looking. word_count([_ | Rest], N) -> word_count(Rest, N).
Again, it appears to cover all cases; for some reason I don’t yet understand, it doesn’t work if I use a space character instead of 32. Even if I do something like:
space = 32.
…
word_count([_, space | Rest]) …
doesn’t work. WTH.
Recent Comments