erl_interface and lists

Kent Boortz kent@REDACTED
Tue May 27 14:56:23 CEST 2003


Serge Aleynikov <serge@REDACTED> writes:
> Could someone shed some light on how to decode lists' elements (other
> than head and tail) in erl_interface.  The examples included in the
> docs are pretty clear on how to decode tuples and atoms, but I can't
> seem to find any reference for functions dealing with retrieval of an
> N'th element of a list.
> 
> Suppose the Erlang side of the interface is passing a tuple to a C port:
> {init, [a, b, c]}
> 
> ETERM *tuple = erl_decode(buf);
> ETERM *atom  = erl_element(1, tuple);
> ETERM *list  = erl_element(2, tuple);
> 
> Then what I'd like to do is to iterate over each element of the list:
> 
> for (int i=0; i < erl_length(list); i++) {
>    do_smthng_with_item(ERL_NTH_ELEMENT(i, list));
> }
> 
> So, how can I implement ERL_NTH_ELEMENT()?

In the erl_interface API lists are stored as cons cells (same as in
the emulator). This means that a list

  [a, b, c]   is the same as    [a | [b | [c | []]

I haven't tested this code

  ETERM *list = erl_decode(buf);
  ETERM *element; 

  while (list && (element = erl_hd(list))) {
    /* do something with element */
    list = erl_tl(list);
  }

Note that this will increment the reference counter on the list
elements and the list cons cells. If you don't want to alter the
counters you can use the macros ERL_CONS_HEAD(list) and
ERL_CONS_TAIL(list),

kent



More information about the erlang-questions mailing list