Search code examples
listexceptiondictionaryerlangnormalize

Erlang exception error using BIF and lists:maps


Our task was to write a function normalize/1 which divides each element in the list my max element.

Here's my code so far (instead of my own written function, I used built in one to find max):

normalize(List) -> 
    Z = lists:max(List),
    [ X / Z  || X  <- List].

Now I have to write a function called normalize2 which does the same as normalize/1 but uses lists:map/2

normalize2(List) -> lists:map(fun normalize/1, List).

Terminal shows this:

test3:normalize2([1,2,3,5]). ** exception error: no function clause matching lists:max(1) (lists.erl, line 313) in function test3:normalize/1 (test3.erl, line 85) in call from lists:map/2 (lists.erl, line 1224)

UPDATE:

Heres find_max/1:

find_max([T]) ->
    T;
find_max([H,H1|T]) when H > H1->
    find_max([H,T]);
find_max([_H,H1|T])->
    find_max([H1|T]).

If I used ^ find_max, terminal shows me:

test3:normalize2([1,2,3,5]). ** exception error: no function clause matching test3:find_max(1) (test3.erl, line 137) in function test3:normalize/1 (test3.erl, line 84) in call from lists:map/2 (lists.erl, line 1224)

Line 137 is find_max([T]) -> T; Line 84 is Z = find_max(List),


Solution

  • lists:max return max value from a list. It means argument of this function must be list.

    When you call lists:map it means -- apply some function ('normailze' in your case) to each list item. But List items are integers. That is why the line Z=lists:max(List) throws an exception (variable List is not list actually).

    you can use lists:map as replacement of list comprehension. Kind of

    normalize2(List) -> Z = lists:max(List), lists:map( fun(X) -> X/Z end, List).