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

I have a variable that can contain a list of strings or just a string. Is there a good way to tell what I'm dealing with?

"192.168.1.18" vs. ["192.168.1.18", "192.168.1.19"]

In any case, I want to use the bits involved.

+5
source share
3 answers

How you do it, a lot depends on what you plan to do with the result, or rather, how you plan to do it. Therefore, if you are interested in bits:

case MyVar of
    [First|Rest] when is_list(First) -> ... First,Rest ...;
    _ -> ... MyVar ...
end

or if you are not interested in pulling a line / list of lines that you could do:

if is_list(hd(MyVar)) -> ... ;
   true -> ...
end

? - , , , . / , .

+5

- :

case X of
    [List|_] when is_list(List) ->
        list_of_lists;
    List when is_list(List) ->
        list;
    _ ->
        not_a_list
end
+1

Erlang , , io_lib.

IP- - io_lib: latin1_char_list (Term) http://erlang.org/doc/man/io_lib.html#latin1_char_list-1

io_lib: latin1_char_list/1 :

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.

Unicode, io_lib: char_list (Term) http://erlang.org/doc/man/io_lib.html#char_list-1

io_lib: char_list/1 :

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.

io_lib .

Please note that if some new erlang function is not available in your version supported by your project, you can simply copy the implementation of new erlang versions and add them to your own module. Find the latest erlang / lib / * / src source code and just get the new features you need.

+1
source

All Articles