Erlang Example: Min and Max Element of a List

May 28, 2008 - 3 minute read -
erlang exercises

This is part of a series on the Erlang Exercises which is a great set of programming problems that challenge you to implement solutions to some common Erlang problems. I'm going to share some of my solutions to these problems.

Simple recursive programs

1. Write a function lists1:min(L) which returns the mini- mum element of the list L. 2. Write a function lists1:max(L) which returns the maximum element of the list L.

(I'm only showing the max version since the min is basically just the change of the guard clause.)

-module(mylists).
-export([max/1]).
max([H|T]) ->
    max(H, T).
max(M, []) ->
    M;
max(M, [H|L]) when M > H ->
    max(M, L);
max(_M, [H|L]) ->
    max(H,L).

Explanation

max([H|T]) This code is composed of a public, exported function and a private function. max([H|T]) defines a function that takes a list. The slightly funny notation [H|T] is an operation that removes the head value (the zeroth element] from a list and assigns the head value to H and the remainder of the list to T. Think of the list as a stack, and you've just popped the stack. This method then delegates the remainder of the work to the internal, 2 value max function.

max(M, [H|L]) when M > H -> This method is the main part of the internal, 2 value max function. The interesting piece here is when M > Hmax(_M, [H|L]) -> which acts as a fall-through because the ones that don't match the first will call this. You can see those two functions take either M or H and pass that as the current Max value.

max(M, []) -> The final piece of the internal max function is max(M, []) ->. This is the end state of the function. The [] clause in the function arguments pattern matches an empty list. Based on those previous 2 parts of the function definition this is fulfilling the final case where the current max value has been compared to the last element in the list.

Example

List = [1,2,4,6,5].
mylists:max(List).

So what happens is:

  1. max([1 | [2,4,6,5]])
  2. max(1, [2 | [4,6,5]])
  3. max(2, [4 | [6,5]])
  4. max(4, [6 | [5]])
  5. max(6, [5 | []]) when M > H
  6. max(6, [])