[erlang-questions] List to proplist?
Richard O'Keefe
ok@REDACTED
Tue Oct 21 01:37:15 CEST 2008
On 20 Oct 2008, at 5:56 pm, Edwin Fine wrote:
> I know it would be easy to write a pattern-matching-style function,
> but I wanted to do it without having to define a new function,
>
> element(1, lists:mapfoldl(fun(_,[X,Y|T]) -> {{X,Y}, T} end, L,
> lists:seq(1, length(L) div 2))).
But you just defined a new function and a pattern-matching one
at that.
The obvious function is
to_proplist([Key,Val|Rest]) ->
[{Key,Val} | to_proplist(Rest)];
to_proplist([]) ->
[].
Now let's pretend that you've heard of "unfold",
maybe even read
http://debasishg.blogspot.com/2007/11/fun-with-unfold-in-erlang.html
Let's copy the unfold function from there.
unfold(Seed, Predicate, Transformer, Incrementor) ->
unfold(Seed, Predicate, Transformer, Incrementor, []).
unfold(Seed, Predicate, Transformer, Incrementor, Acc) ->
case Predicate(Seed)
of false -> lists:reverse(Acc)
; true -> unfold(Incrementor(Seed),
Predicate,
Transformer,
Incrementor,
[Transformer(Seed)|Acc])
end.
Now it's fairly straightforward:
to_proplist(Even_List) ->
unfold(Even_List,
fun (L) -> L =/= [] end,
fun ([Key,Val|_]) -> {Key,Val} end,
fun ([_,_|Rest]) -> Rest end).
When you want to generate a list, an unfold is often what
you want rather than a fold.
I don't suppose we could have unfold/4 in the lists module,
could we?
More information about the erlang-questions
mailing list