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?
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.
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.
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.
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 _
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With