Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warnings about unused variables in Erlang

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?

like image 694
Dylan White Avatar asked Dec 06 '08 02:12

Dylan White


People also ask

Why is unused variable an error?

Unused variable warnings are emitted during compiletime and should be a hint to you as the developer, that you might have forgotten to actually process a value that you have bound to a name. Thats the main reason for the warning.

Which symbol is used to declare unbound values in Erlang?

In Erlang, all the variables are bound with the '=' statement. All variables need to start with the upper case character. In other programming languages, the '=' sign is used for the assignment, but not in the case of Erlang.

What does unused variable mean in C?

No nothing is wrong the compiler just warns you that you declared a variable and you are not using it. It is just a warning not an error. While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.


1 Answers

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 _).

like image 157
Adam Lindberg Avatar answered Sep 18 '22 16:09

Adam Lindberg