Return maximum list

I am trying to return the maximum 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 I'm struggling to tie Erlang.

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

+4
source share
5 answers

Erlang is one of those languages ​​in which it is easier for me 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 name it like this:

 {ok, Max} = list_max(MyList). 
+4
source

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

The short answer is that you cannot. Variables in Erlang cannot be changed after assignment.

A slightly longer answer is that although you cannot change a variable inside a particular function call, you can always do the recursion yourself. Optimized tail recursion in Erlang.

In the code example below, list_max will only look at the first two elements of the list. In the fourth and fifth sentences, everyone should again call list_max, with a new Temp value in the first parameter. This is common in functional languages. In this case, Temp is known as the Accumulator (I often call the Acc variable to reflect this usage, but of course you can name it however you want).

Let me show you another solution that can be seen as β€œbetween” the Macelo answer and the stmi 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 dropped the sentence that detects an empty list because I don't think it really buys you a lot - although now it will throw an exception if you call it with an empty list.)

+3
source

Sorry, maybe I missed something. You are looking for:

 lists:max(List). %% Find the max in List 
+2
source

You can also express than the built-in functions:

 -module(list_max). -compile(export_all). list_max([]) -> none; list_max([H | T] = List) -> lists:foldl(fun erlang:max/2, H, T); list_max(_) -> badarg. 
+1
source

Erlang is one task, so you cannot change "variables". You can only create new ones.

My recommendation is to see the list module. Inside lists.erl you will find:

 max([H|T]) -> max(T, H). max([H|T], Max) when H > Max -> max(T, H); max([_|T], Max) -> max(T, Max); max([], Max) -> Max. 

You are not updating the Max variable (Temp in your example), but rather calling the function with a new value or returning it from the function.

Easy peasy ... :-)

+1
source

All Articles