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.
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.
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.
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.
Why would you need to separate these? Strings are lists in erlang (most of the time).