tags:

views:

124

answers:

3

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 lists or strings.

+4  A: 

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

Amadiro
Yes, I would like to hear how others do this too. With your string example were you adding "state" to the string by changing the status for the different stages? I didn't quite understand
Zubair
Yes, basically. I tagged the string, and gave it some extra metainformation, which I can conveniently match against later on. All intermediate functions either have to pass the string along unchanged, or process it properly.
Amadiro
+2  A: 

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}.

Alexey Romanov
+1  A: 

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.

Weasel