[erlang-questions] List to proplist?

Edwin Fine erlang-questions_efine@REDACTED
Tue Oct 21 02:13:45 CEST 2008


Thanks for your very informative answer.

On Mon, Oct 20, 2008 at 7:37 PM, Richard O'Keefe <ok@REDACTED> wrote:

>
> 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'll pretend that you actually answered, and maybe even read, the question I
was asking. Somehow, Richard Carlsson managed to do that, without inventing
new library functions, so it couldn't have been too obscure and
badly-worded. However, I see now that I asked the wrong question, or phrased
it incorrectly, so thank you for setting me straight. I apologize for not
having heard of unfold, and for not having read every blog in existence that
contained something relevant to my question prior to wasting people's
valuable time on this list by asking it in the first place.


> I don't suppose we could have unfold/4 in the lists module,
> could we?
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081020/6af50a93/attachment.htm>


More information about the erlang-questions mailing list