[erlang-questions] how: Another library flatten function?

caio ariede caio.ariede@REDACTED
Fri Feb 26 23:15:36 CET 2010


Do you mean lists:reverse?

Caio Ariede
http://caioariede.com/


2010/2/26 黃耀賢 (Yau-Hsien Huang) <g9414002.pccu.edu.tw@REDACTED>

> On Fri, Feb 26, 2010 at 9:58 PM, Bengt Kleberg <bengt.kleberg@REDACTED
> >
>  wrote:
>
> > Greetings,
> >
> > I have the following list: ["asd",[["Flow","kalle"]],["Sub","F"]]
> > I would like to flatten it to: ["asd","Flow","kalle","Sub","F"]
> > lists:flatten/1 is too effective. It gives me: "asdFlowkalleSubF"
> >
> > Is there another flatten somewhere?
> >
>
> The following page tells us that lists:flatten/1 is expensive and even more
> expensive than ++.
> http://www.erlang.org/doc/efficiency_guide/listHandling.html
> And in some cases, lists:append/1 is used for avoiding calling the
> lists:flattten/1.
>
> On Fri, Feb 26, 2010 at 11:50 PM, Dmitry Belayev <rumata-estor@REDACTED>
> wrote:
>
> > You can write your own:
> >
> > f(List) ->
> >   lists:reverse(f(List, [])).
> >
> > f([], A) ->
> >   A;
> > f([L|_]=I, A) when is_number(L) ->
> >   [I | A];
> > f([H|Tail], A) ->
> >   f(Tail, f(H, A)).
> >
>
> My solution without lists:reverse/1,
>
> flatten([]) ->
>    [];
> flatten([[S|Ss]|Xs]) when is_number(S) ->
>    [[S|Ss]|flatten(Xs)];
> flatten([Xs|Ys]) ->
>    flatten(Xs ++ Ys).
>
> Every string occurring in the head of a list is picked out first, or a head
> of a list which is also
> a list is appended. Though it looks not efficiency, the page
> http://www.erlang.org/doc/efficiency_guide/myths.html#id2253656
> says that it's somewhat OK.
>
> On Sat, Feb 27, 2010 at 1:29 AM, Jayson Vantuyl <kagato@REDACTED> wrote:
>
> > Or:
> >
> > flat(L) -> lists:map(fun lists:flatten/1,L).
> >
> > Or:
> >
> > flat(L) -> [ lists:flatten(X) || X <- L ].
> >
> > Sent from my iPhone
> >
> >
> >
> lists:flatten/1 is more expensive than ++.
>


More information about the erlang-questions mailing list