typestar

Recursion in Erlang

The loop is a function calling itself; accumulators keep it tail.

%% Recursion is the loop; the accumulator keeps it a tail call.
total_minutes([], Acc) ->
    Acc;
total_minutes([{_, Minutes} | Rest], Acc) ->
    total_minutes(Rest, Acc + Minutes).

count_over([], _, Acc) -> Acc;
count_over([{_, M} | Rest], Limit, Acc) when M > Limit ->
    count_over(Rest, Limit, Acc + 1);
count_over([_ | Rest], Limit, Acc) ->
    count_over(Rest, Limit, Acc).

main(_) ->
    Log = [{"5560199", 12}, {"5560142", 3}, {"5560170", 21}],
    io:format("Billed minutes: ~p~n", [total_minutes(Log, 0)]),
    io:format("Long calls: ~p~n", [count_over(Log, 10, 0)]).

How it works

  1. The empty-list clause returns the accumulator: the base case.
  2. Each step peels one element and recurses on the rest.
  3. A guard splits counting clauses by the limit.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
554
Tokens
182
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 182 seconds.

Type this snippet

Step 1 of 3 in Recursion & comprehensions, step 8 of 31 in Language basics.

← Previous Next →

Recursion in other languages