is_proplist in erlang?

2019-02-26 11:15发布

问题:

How can get the type of a list. I want to execute the code if the list is proplist. Let us say L = [a,1,b,2,c,3, ...]. Is the list L, I'm converting it to proplist like

L = [{a,1}, {b,2}, {c,3}, ...].

How can I determine whether the list is a proplist? erlang:is_list/1 is not useful for me.

回答1:

You can use something like:

is_proplist([]) -> true;
is_proplist([{K,_}|L]) when is_atom(K) -> is_proplist(L);
is_proplist(_) -> false.

but necessary to consider that this function cannot be used in guards.



回答2:

You'd need to check whether every element of the list is a tuple of two elements. That can be done with lists:all/2:

is_proplist(List) ->
    is_list(List) andalso
        lists:all(fun({_, _}) -> true;
                     (_)      -> false
                  end,
                  List).

This depends on which definition of "proplist" you use, of course. The above is what is usually meant by "proplist", but the documentation for the proplists module says:

Property lists are ordinary lists containing entries in the form of either tuples, whose first elements are keys used for lookup and insertion, or atoms, which work as shorthand for tuples {Atom, true}.



标签: erlang