Return of Erlang

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.


% Only export the version that takes just the list.

% 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.

Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

You may use these HTML tags and attributes:

<a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: