Chapter 6. Lists

Étude 6-1: Recursive Iteration through a List

In a module named Stats, write these functions:

  • minimum/1, which takes a list of numbers as its argument and returns the smallest value.
  • maximum/1, which takes a list of numbers as its argument and returns the largest value.
  • range/1, which takes a list of numbers as its argument and returns a list containing the maximum and minimum values in the list.

Here’s the pseudocode for minimum/1.

  • Split the list into the first number and the remainder of the list using the cons operator |.
  • Call function minimum/2, which takes a list as its first argument and the “smallest number so far” (the current candidate) as its second argument. Use the remainder of the list (which you extracted in the previous step) as the first argument to minimum/2, and the first item in the list as the second argument.

Here’s the pseudocode for minimum/2.

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

Of course, the code for maximum/1 is indentical to that of minimum/1 except that it ...

Get Études for Elixir 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.