Erlang Thursday – lists:max/1

Today’s Erlang function is lists:max/1.

lists:max/1 takes one argument, a list of at least one term, and returns the item that has the greatest value when compared to the other items in the list. The list can be composed of any Erlang term:

lists:max([1, 39, 7, 63, 27, 52, 16]).
% 63
lists:max([q, w, a, r, c, f, m, b]).      
% w
lists:max([[1, 2, 3], [1, 2, 4]]).
% [1,2,4]

Erlang has a distinct order between the different types of terms,

number < atom < reference < fun < port < pid < tuple < list < bit string

allowing for the list passed to lists:max/1 to be comprised of disparate types.

lists:max([1, 2, 3, 4, a]).         
% a
lists:max([1, a, [foo, bar], {baz}]).
% [foo,bar]

And because a string in Erlang is just a list of numbers under the covers, we can even compare strings.

lists:max(["foo", "bar", "baz", "snafu"]).

If you pass an empty list to lists:max/1 a no function clause matching error will be raised, since it expects the list to be at least composed of one term.

** exception error: no function clause matching lists:max([]) (lists.erl, line 326)

What are some of your favorite Erlang functions, or even just ones you would like to see a future Erlang Thursday post about?

And don't forget to check out the last Tuesday's Ruby Tuesday on Enumerable#max, if you would like a comparison between Erlang's max function and Ruby's max method.