Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning the max of a list

I am trying to return the max of a list.

I have the following code

list_max([]) ->
    [];
list_max([H|T]) ->
    list_max(H, T).
list_max(Temp, []) ->
    Temp;
list_max(Temp, [H|T]) when H > Temp ->
    Temp = H;
list_max(Temp, T).

But am struggling to relate to Erlang.

How do I assign something to temp and replace it to the highest?

like image 203
some_id Avatar asked Sep 22 '10 11:09

some_id


Video Answer


3 Answers

Erlang is one of those languages in which I find it easier to show than to explain.

list_max([]   ) -> empty;
list_max([H|T]) -> {ok, list_max(H, T)}.

list_max(X, []   )            -> X;
list_max(X, [H|T]) when X < H -> list_max(H, T);
list_max(X, [_|T])            -> list_max(X, T).

and call it thus:

{ok, Max} = list_max(MyList).
like image 153
Marcelo Cantos Avatar answered Oct 19 '22 08:10

Marcelo Cantos


How do I assign something to temp and replace it to the highest?

The short answer is that you can't. Variables in Erlang cannot be changed once assigned.

The slightly longer answer is that, while you can't change a variable inside a particular function call, you can always self-recurse. Tail-recursion in Erlang is optimized.

In the example code that you provided, list_max will only ever look at the first two elements of the list. The fourth and fifth clauses should each call list_max again, with the new value of Temp in the first parameter. This is a common thing to do in functional languages. In this case, Temp is known as an Accumulator (I often name the variable Acc to reflect this use, but of course you can name it whatever you want).

Let me show another solution that could be seen as "in between" Macelo's answer and stmi's answer:

list_max( [H|T] ) -> list_max( H , T ).

list_max( X , []    ) -> X;
list_max( X , [H|T] ) -> list_max( erlang:max(H, X) , T ).

(I also ditched the clause that detects the empty list, because I don't think it really buys you much - though it will now throw an exception if you call it with an empty list.)

like image 27
Daniel Yankowsky Avatar answered Oct 19 '22 08:10

Daniel Yankowsky


Sorry, maybe I'm missing something. Are you looking for:

lists:max(List). %% Find the max in List
like image 4
Mazen Harake Avatar answered Oct 19 '22 08:10

Mazen Harake