Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a list is a just a string or a list of strings?

Tags:

erlang

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.

like image 892
Fylke Avatar asked Sep 10 '09 16:09

Fylke


Video Answer


2 Answers

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.

like image 131
rvirding Avatar answered Nov 15 '22 08:11

rvirding


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
like image 35
legoscia Avatar answered Nov 15 '22 10:11

legoscia