Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_proplist in erlang?

Tags:

erlang

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.

like image 613
Laxmikant Ratnaparkhi Avatar asked Mar 04 '14 10:03

Laxmikant Ratnaparkhi


People also ask

How do I check if a list is empty in Erlang?

This is the function that is called: set_viewer_values(Value, ViewerSet) -> if ViewerSet /= empty_set -> lists:map(fun(ViewerPid) -> ViewerPid ! {self(), set_value, Value} end, ViewerSet) end.

How do I find the length of a list in Erlang?

You can use length() to find the length of a list, and can use list comprehensions to filter your list. num(L) -> length([X || X <- L, X < 1]). Working example: % list counter program -module(listcounter).

What are the two types of lists available in Erlang?

You can't seriously program in a language just with scalar types like numbers, strings and atoms. For this reason, now that we have a basic knowledge of Erlang's syntax and variables, we have to delve into two basic vector types: tuples and lists.

How do I add a list in Erlang?

The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets.


2 Answers

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.

like image 67
P_A Avatar answered Oct 18 '22 23:10

P_A


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

like image 43
legoscia Avatar answered Oct 18 '22 23:10

legoscia