Jazzbaron
Jazzbaron

Reputation: 75

Erlang: Identifying the max element in a list

I'm kind of new to Erlang, but here goes. I want to create an auxiliary function that takes the highest positive integer in a list and returns this value. My approach to this, in code, is as follows:

-module(function).
-export([normalize/1]).

    normalize(List) -> normalize(List, 0).

    normalize([], N) -> N;                                
    ​normalize([H|T], N) when H > N -> normalize(T, H==N).

I keep getting a syntax error on the last line (suspecting something is wrong with the guard) and also 'function normalize/2 is undefined' on the first line. How do I make this work?

Upvotes: 1

Views: 1420

Answers (1)

Ahmad Sherif
Ahmad Sherif

Reputation: 6223

I'm not sure why you're comparing H to N (H==N) in the last line, but to fix your approach all you need is to replace H==N with just H. This would make it work for lists like [1,2,3], but it would fail for lists like [3,1,2] or [1,1,1], because the guard check would fail.

To fix that last case you need to add another function clause with guard check like H =< N. Building on your code, here is a complete version

-module(function).
-export([normalize/1]).

normalize(List) -> normalize(List, 0).

normalize([], N) -> N;
normalize([H|T], N) when H > N -> normalize(T, H);
normalize([H|T], N) when H =< N -> normalize(T, N).

However, there's a function that finds the max element of a list lists:max/1, and I highly recommend you take a look at its implementation; it is really simple.

Also your example doesn't include a list comprehension, so I updated the question title and tags. And one last thing, the name normalize is not kinda good for the function purpose :).

Upvotes: 5

Related Questions