tags:

views:

153

answers:

3

I am writing a program that can have either a list or a string as an argument. How can I tell the difference between a string and a list programmatically in Erlang. Something like:

print(List) -> list; 
print(String) -> string.
+4  A: 

io_lib:printable_list might be what you are looking for. However it doesn't handle unicode only latin-1 encodings. If you need to detect unicode strings I think you might be out of luck. The best bet is pseudo typing your lists like so: {string, [$a, $b, $c]}. Kind of a build your types.

use a constructor like so string(L) when is_list(L) -> {string, L}.

and just use that typing construct all through your app.

On the other hand you could just treat all strings as just lists and not make the distinction.

Jeremy Wall
Thanks. yes, I did think of this pseudo typing, but I didn't know if it was a good way to do things in Erlang.
Zubair
Another option I've seen used is to keep all strings as binaries.
Jeremy Wall
+1  A: 

Best thing what you can do is tagging your structures as Jeremy Wall suggested. Anyway you can decide check input to your module/subsystem/application/...

is_string([]) -> true;
is_string([X|T]) -> is_integer(X) andalso X>=0 andalso is_string(T);
is_string(_) -> false.

Unfortunately it is expensive operation and you can't use it in guards.

Hynek -Pichi- Vychodil
But then a list would show up as a string in your example, is that correct?
Zubair
I don't understand question. Do you mean something like `new_string(X) -> true = is_string(X), {string, X}.`? So answer is yes.
Hynek -Pichi- Vychodil
A: 

Why would you need to separate these? Strings are lists in erlang (most of the time).

Weasel
The most common reason you would need to do this is a nested lists in a tree where some of the sub-lists are strings which need to be treated as a list entry not a subtree. Without tagging the list operations like flatten and tree traversal become much more difficult.
Jeremy Wall
Right, in that case I second your solution with pseudo-typing as it's a way of building your own way of control flow.
Weasel