<div dir="ltr">Hi all,<br><br>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).<br>
<br>For example, the function would do this: f([1,2,3,4,5,6,7,8]) -> [{1,2},{3,4},{5,6},{7,8}].<br><br>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.<br>
<br>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):<br><br><span style="font-family: courier new,monospace;"></span><span style="font-family: courier new,monospace;">    element(1, lists:mapfoldl(fun(_,[X,Y|T]) -> {{X,Y}, T} end, L, lists:seq(1, length(L) div 2))).</span><br>
<br>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...<br>
<br>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.<br><br>Regards,<br>Edwin Fine<br><br></div>