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.)
source share