For example, to denote a String I could use:
{string,"hjggjhhggJ"}
and a list would be:
{list, [1,2,3]}
: I guess I have found that I am running into situations where I need types, for example to distinguish between strings and lists and I am not sure how to proceed. I do however want to use whatever technique I choose everywhere in my Erlang application for consistency, and not just for strings and lists. Any advice?
Update: An example of where I use this is when I store data values in the Riak datastore which lets you store either li开发者_如何转开发sts or strings.
If you need to distinguish that way -- Yes, you can do that. Though, the general idea of dynamic typing is not to discriminate for types, unless absolutely necessary. (I find it debatable, though, how much this applies to a non-oop language like erlang -- I would love to hear what other people think about that topic)
Sometimes, however, it can be quite useful to have a distinction. In one of my projects, I had a string, which would go through different phases of escaping, depending on what was supposed to happen with the input string. Outputting a String that wasn't escaped properly, could pose a security risk. To make this safer, I made it a tagged tuple:
{my_string, false, false, ActualString}
And when one stage of escaping/processing has happened, I could switch the boolean:
{my_string, true, false, ActualString}
and then the output function that receives the string, can match for certain criteria:
output_html_escaped_string({my_string, true, _, ActualString}) -> ...
This way the function would raise an exception if I pass it an unprocessed string by accident (And I remember that did happen once or twice :).
Yes. This is also used for distinguishing multiple constructors of the same type (not that there is really a difference in Erlang). For example, many functions in the standard library are specified to return either {error, Reason}
or {ok, Value}
.
Not sure it's what you need but you can use guard expressions in order to distinct between types. Please provide more input/example on your point so I could perhaps help more.
in general you probably don't want to do {string, "ABC"} what is probably more useful would be something like {username, "ABC"} or the like where the tag is not what kind of data it is in terms of string or list, but how your application is going to use that data. That way you can pattern match on what the data means, not what it is
You can use guards (though a string in erlang is a list of chars)
精彩评论