[erlang-questions] List to proplist?
Ulf Wiger
ulf@REDACTED
Mon Oct 20 08:27:30 CEST 2008
Well, the obvious way to do it ought to be:
to_proplist([K,V | T]) -> [{K,V} | to_proplist(T)];
to_proplist([]) -> [].
BR,
Ulf W
2008/10/20 Edwin Fine <erlang-questions_efine@REDACTED>:
> Hi all,
>
> I was wondering what the most elegant and efficient way would be to take a
> list containing an even number of elements and convert it into a proplist,
> using only Erlang library functions? This is really a learning thing for me
> (how to think in Erlang) rather than an urgent question, but it is based on
> a real need (having a flat list of key/value pairs and wanting it in
> proplist form).
>
> 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. I thought there
> might be a proplists:from_list/1 function, but I couldn't find one.
>
> The best I could come up with is this (it's ok to assume that there will be
> an even number of elements in L):
>
> element(1, lists:mapfoldl(fun(_,[X,Y|T]) -> {{X,Y}, T} end, L,
> lists:seq(1, length(L) div 2))).
>
> It seems like a bit of a perversion of the idea of foldl, being used to
> "unaccumulate". I'm also not really happy with having to generate another
> list using lists:seq, especially if L is long, but I can't think of a better
> way to drive the foldl part with the right number of elements. I thought of
> splitting L in half for this, but what if L has large elements? Wouldn't I
> be using much more memory than a simple list of integers, or would it
> internally be a list of pointers to half of the elements of L? Actually,
> that would almost always be bigger than a list of integers on a 64-bit
> system...
>
> Is there a better way to do this given the stated constraints? If so, I'd
> appreciate it if you'd share it with me.
>
> Regards,
> Edwin Fine
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
More information about the erlang-questions
mailing list