Recursion Examples in Erlang

I was watching an Erlang video (free trial) before bed last night and there were some examples of recursive patterns that people might find interesting:

%%% Recursive patterns
-export([double/1, member/2, even/1, average/1, average_acc/1]).

%% Double each number in a list
double([H|T]) -> [2*H|double(T)];
double([]) -> [].

%% Is element a member of a list?
member(H, [H|_]) -> true;
member(H, [_|T]) -> member(H, T);
member(_, []) -> false.

%% Return the even numbers in a list
even([H|T]) when H rem 2 == 0 -> [H|even(T)];
even([_|T]) -> even(T);
even([]) -> [].

%% Traverses the list multiple times
average(X) -> sum(X) / len(X).

%% not tail recurisve
sum([H|T]) -> H + sum(T);
sum([]) -> 0.

%% not tail recurisve
len([_|T]) -> 1 + len(T);
len([]) -> 0.

%% Recursion with accumulators
%% Traverses the list once
%% Executes in constant space (tail recursive)
%% average([]) will cause runtime error, because average_add([]) isn't
%% handled.
average_acc(X) -> average_acc(X, 0, 0).

average_acc([H|T], Length, Sum) ->
    average_acc(T, Length+1, Sum+H);
average_acc([], Length, Sum) ->

More resources:

1 Like

– in haskell here’s a recursive double func:
doubler [] = []
doubler (x:xs) = (x*2) : doubler xs

– note the : is cons (prepend)

1 Like

Nice, they look very similar.

In Erlang:

[H|T] = [1,2,3,4].  % H=1, T=[2,3,4]
[1|[2,3,4]].        % [1,2,3,4]

Tail recursion is super cool! I was recently learning about it in Scala for a job I was interested in. I wish it was supported in JavaScript which I program in more regularly. It seems like it has been talked about for a while, but so far not been added to the standard.

1 Like

I was trying to solve some of the Erlang puzzles on and got stuck so I started reading the Learn You Some Erlang book – it has been sitting on my shelf for too long. :turtle:

The pattern matching is interesting. I saw this in someone’s solution to a coding puzzle:

Number. % 21
Rules.  % [{3,"Pling"},{5,"Plang"},{7,"Plong}]

%% extract the sounds for numbers that have the keys as factors
L = [Sound || {Factor, Sound} <- Rules, Number rem Factor == 0].
%% ["Pling","Plong"]

%% since strings are lists, a list of strings can be flattened to join them
lists:flatten(L).  % "PlingPlong"

He walks through those examples in this video: