[erlang-questions] List to proplist?

Edwin Fine erlang-questions_efine@REDACTED
Mon Oct 20 18:46:06 CEST 2008


On Mon, Oct 20, 2008 at 3:06 AM, Richard Carlsson <richardc@REDACTED> wrote:

> Edwin Fine wrote:
> > For example, the function would do this: f([1,2,3,4,5,6,7,8]) ->
> > [{1,2},{3,4},{5,6},{7,8}].
> >
> > 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, in as compact
> > a way as possible while still keeping it reasonably efficient.
>
> element(1, lists:foldr(fun (X,{As,[]}) -> {As,[X]}; (X,{As,[Y]}) ->
> {[{X,Y}|As],[]} end, {[],[]},  List)).
>

That's beautiful - thanks! That's exactly what I was looking for - an idiom.
I never thought of having two accumulators. I see that the principle you
used could be extended to making triples instead of pairs, and so on:

element(1, lists:foldr(fun(Z,{As,[]}) -> {As,[Z]};
                          (Y,{As,[Z]}) -> {As,[Y,Z]};
                          (X,{As,[Y,Z]}) -> {[{X,Y,Z}|As],[]}
                       end,
                       {[],[]},
                       List))

Ulf, thanks for your response, too!

Regards,
Edwin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081020/f495f7ac/attachment.htm>


More information about the erlang-questions mailing list