Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Erlang implements different functions to test if a list is a flat list in module io_lib.

One good choice for checking your particulary IP strings is io_lib:latin1_char_list(Term) http://erlang.org/doc/man/io_lib.html#latin1_char_list-1

io_lib:latin1_char_list/1 function implementation is:

latin1_char_list([C|Cs]) when is_integer(C), C >= $\000, C =< $\377 ->
      latin1_char_list(Cs);
latin1_char_list([]) -> true;
latin1_char_list(_) -> false.

If you want to test for flat unicode lists you can use io_lib:char_list(Term) http://erlang.org/doc/man/io_lib.html#char_list-1

io_lib:char_list/1 function implementation is:

char_list([C|Cs]) when is_integer(C), C >= 0, C < 16#D800;
       is_integer(C), C > 16#DFFF, C < 16#FFFE;
       is_integer(C), C > 16#FFFF, C =< 16#10FFFF ->
    char_list(Cs);
char_list([]) -> true;
char_list(_) -> false.

Check the io_lib module documentation for other similar functions.

Notice that if some new erlang function are missing from your current project supported erlang version you can simply copy the implementation new erlang versions provides and add them into a module of your own. Search the latest erlang/lib/*/src source code and simply get the new functions you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top