I have a variable that can either contain a list of strings or a just a string. Is there a good way to tell what kind I'm dealing with?
"192.168.1.18" vs. ["192.168.1.18", "192.168.1.19"]
In either case I want to use the bits involved.
How you do it depends a lot on what you plan to do with the result, or rather how you plan to do it. So if you are interested in the bits:
case MyVar of
[First|Rest] when is_list(First) -> ... First,Rest ...;
_ -> ... MyVar ...
end
or if you are not interested in actually pulling apart the string/list of strings you could do:
if is_list(hd(MyVar)) -> ... ;
true -> ...
end
Have I understood you correctly here? I have not put any code in to actually check that what should be strings actually are strings, this should have be done earlier. an alternative would be when generating this string/list of strings to always put it into one of the formats.
I sometimes write something like:
case X of
[List|_] when is_list(List) ->
list_of_lists;
List when is_list(List) ->
list;
_ ->
not_a_list
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With