erlang 如何确定一个列表是一个字符串还是一个字符串列表?

kuarbcqp  于 2022-12-08  发布在  Erlang
关注(0)|答案(4)|浏览(290)

我有一个变量,它既可以包含一个字符串列表,也可以只包含一个字符串。有没有一个好的方法来判断我正在处理的是哪种类型的变量?

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

在这两种情况下,我都希望使用所涉及的位。

ergxz8rk

ergxz8rk1#

如何做很大程度上取决于你打算如何处理结果,或者更确切地说,取决于你打算如何做。所以,如果你对这些细节感兴趣:

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

或者,如果您对实际拆分字符串/字符串列表不感兴趣,您可以执行以下操作:

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

我理解的对吗?我没有写任何代码来检查字符串是否是字符串,这应该早一点完成。另一种方法是在生成字符串/字符串列表时,总是将其放入其中一种格式。

hjzp0vay

hjzp0vay2#

我有时会写这样的话:

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

cxfofazt3#

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.

nnt7mjpx

nnt7mjpx4#

If this distinction needs to be determined in the function head, this is a way to figure this out in the guard:

1> S = "lofa".
2> T = ["hehe", "miez"].

3> is_list(S).
true
4> is_list(T).
true

Erlang characters are integers,

5> hd(S). % => 108    
6> Y = "よし". % => [12424,12375]

so, to check for string inputs:

7> (fun
7>     ([H|_] = L) when erlang:is_integer(H) -> yay;
7>     (_) -> nono
7>  end
7> )(S).
yay

8> (fun([H|_] = L) when erlang:is_integer(H) -> yay; (_) -> nono end)(T).
nono

Personally, I find the above version more intuitive than

9> (fun([H|_] = L) when not(erlang:is_list(H)) -> yay; (_) -> nono end)(Y).
yay
10> (fun([H|_] = L) when not(erlang:is_list(H)) -> yay; (_) -> nono end)(T).
nono

相关问题