5

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.

Laxmikant Ratnaparkhi
  • 4,745
  • 5
  • 33
  • 49

2 Answers2

10

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.

P_A
  • 1,804
  • 1
  • 19
  • 33
  • Lists like `[a]` and `[a, b]` should also be considered proplists. – Ning Mar 04 '14 at 11:11
  • also keys are not necessarily atoms, can be binary, string/list too. A proplist of `[{<<"Foo">>, bar}, {<<"OMG">>, omg}]` will fail this – Máté Mar 04 '14 at 15:57
5

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}.

legoscia
  • 39,593
  • 22
  • 116
  • 167