Home > Coding > Return of Erlang

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.

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

Categories: Coding Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 218 other followers

%d bloggers like this: