Étude 6-1: Recursive Iteration through a List
In a module named stats
, write a function named minimum/1
. It takes
a list of numbers as its argument and returns the smallest value. This
function already exists in the lists
module (lists:min/1
), but it’s
a good exercise in learning about recursion.
Here’s the pseudocode.
-
Call function
minimum/2
, which takes the list as its first argument and the “smallest number so far” (the current candidate) as its second argument. The starting value will be the head of the original number list passed tominimum/1
. -
When the list passed to
minimum/2
is empty, the final result is the current candidate. This stops the recursion. If the list passed to
minimum/2
is not empty, then see if the head of the list is less than the current candidate.-
If so, call
minimum/2
with the tail of the list as the first argument and the list head (the new “smallest number”) as the second argument. -
If not, call
minimum/2
with the tail of the list as the first argument and the current candidate (still the “smallest number”) as the second argument.
-
If so, call
Unlike most examples in Introducing Erlang, passing an empty list to this function will make it crash. That’s a reasonable thing to do, as an empty list can’t really be said to have a minimum value.
1>
c
(
stats
).
{ok,stats}
2>
N
=
[
4
,
1
,
7
,
-
17
,
8
,
2
,
5
].
[4,1,7,-17,8,2,5]
3>
stats
:
minimum
(
N
).
-17
4>
stats
:
minimum
([]).
** exception error: bad argument
in function hd/1
called as hd([])
in call from stats:minimum/1 (stats.erl, ...
Get Études for Erlang now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.