Wednesday, 15 August 2012

Recursion in Erlang functions -



Recursion in Erlang functions -

i'm having problem understanding piece of code:

{<<"block">>, els} -> jids = parse_blocklist_items(els, []), process_blocklist_block(luser, lserver, jids); #1 parse_blocklist_items([], jids) -> jids; #2 parse_blocklist_items([#xmlel{name = <<"item">>, attrs = attrs} | els], jids) -> case xml:get_attr(<<"jid">>, attrs) of {value, jid1} -> jid = jlib:jid_tolower(jlib:binary_to_jid(jid1)), parse_blocklist_items(els, [jid | jids]); false -> parse_blocklist_items(els, jids) end; #3 parse_blocklist_items([_ | els], jids) -> parse_blocklist_items(els, jids).

i'm not sure function getting called first.

els empty, means #3 gets called first, #2, , #3. right? why need function #3? difference #3 makes if #2 returns jid? i'm lost.

first of all, terminology: #1, #2 , #3 considered different clauses of same function.

this mutual way write recursive function. function transforms some, not all, of elements of input list else.

#1 base of operations case: if there no more input elements, homecoming accumulated output elements (jids).

in #2, first element of input list xmlel record name field <<"item">>. check jid attribute, , if has one, create jid , add together list. note we're doing using recursive call: phone call same function, first argument beingness remaining elements of input list, , sec argument beingness existing output list plus newly added element.

if first element of input list doesn't match pattern in #2, end in #3, skip on , maintain processing rest of list.

if els empty, mention in question, we'll end in clause #1, , won't nail code in #2 , #3.

clauses #2 , #3 similar in both "consume" element input list. difference clause #2 sometimes produces new element output list, while clause #3 never so. have been written single clause; it's question of style , preference.

erlang

No comments:

Post a Comment