views:

329

answers:

3

I recently started Erlang, and I notice I constantly get "Warning: variable X is unused" while compiling. For example, take the following function, which finds the maximum element in a list:

    max([Head|Tail]) ->
       max(Head,Tail).

    max(Element,[Head | Tail]) when Element < Head ->
       max(Head,Tail);
    max(Element,[Head | Tail]) ->
       max(Element, Tail);
    max(Element,[]) ->
       Element.

The compiler warns me that in the 3rd case of the function, Head is unused. How can the function be written without Head?

+4  A: 

This should suppress the warning without being confusing:

max(Element,[_Head | Tail]) ->
   max(Element, Tail);
Dustin
+4  A: 
    max([Head|Tail]) ->
       max(Head,Tail).

    max(Element,[Head | Tail]) when Element < Head ->
       max(Head,Tail);
    max(Element,[_| Tail]) ->
       max(Element, Tail);
    max(Element,[]) ->
       Element.

Should do the trick. The reason being that replacing 'Head' with '_' is syntax for saying that a parameter will be placed there, but I don't need it.

Nicholas Mancuso
+4  A: 

If you name a variable _ instead of Name (e.g. _ instead of Head) the variable will not be bound, and you will not get a warning.

If you name a variable _Name instead of Name (e.g. _Head instead of Head) the variable will be bound, but you will still not get a warning. Referencing a variable beginning with _ in the code is considered very bad practice.

It is recommended to keep the name of the variable to improve the readability of the code (e.g. it is easier to guess what _Head was intended for than just _).

Adam Lindberg
Your last two sentences contradict each other.
Konrad Rudolph
I suspect "using" in this case means "use teh value bound to" rather than "use the _Name construct".
Vatine
With "using a variable" I mean referencing it in code, and "using a variable name" I mean naming it something.
Adam Lindberg