Use of underlined variables in Erlang

Source: Internet
Author: User

In Erlang ' _ ' is a special variable (in fact Erlang should not be called "change" amount, take care of the habit, let's call it), it can replace anything, it is very useful in match, for example:

Erlang Code
    1. {A, _, [B|_], {B}} = {ABC, +, [+], {] }

This means that _ is treated as a placeholder, indicating that there is a value in match, but I don't care what he is.

In Erlang, a variable name that begins with an underscore ' _ ' has a special meaning, in addition to being used as a normal variable (BINDING,MATCH,COMPUTE,COMPARE,ETC), a special tag that tells the compiler that these variables are ignored, It's okay to declare that you're not using/binding (otherwise, compiling will alert by default)

It is a good idea to mark variables that can be ignored by using a variable that starts with an underscore, such as:

Erlang Code
    1. {name,_age}={"Argan",

_age here is actually I do not care about, so use a _ start variable to do match, while reading the code, although the other code does not use the _age, but you can see that this data structure, in addition to name, there is a value of age, very clear expression

However, because a single ' _ ' can match any value, and the match-out value is not available, it is not related to multiple uses in an expression, such as the first example, but if the first example is modified to:

Erlang Code
    1. {A, _int, [B|_int], {B}} = {ABC, +, [+], {] }

Will be wrong, the intention is to express more clearly, _int place is an int value, but there is a trap, [head| Tail] Such a match, the result of the Tail is a list, so the expression above the first _int place is an int 23, the second _int is actually a list [23], so the above expression match will fail.

Leave this record.

Use of underlined variables in Erlang

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.