[erlang-questions] Interleave binaries

Joe Armstrong erlang@REDACTED
Mon Aug 8 21:23:11 CEST 2011


How about

i(A,B) -> i(A,B,[]).

i(<<A1,A2,AT/binary>>,<<B1,B2,BT/binary>>,L) ->
    i(AT, BT, [B2,B1,A2,A1|L]);
i(<<>>,<<>>, L) ->
    list_to_binary(lists:reverse(L)).

The good old "build-it-backwards and then reverse it " trick
O(N) and tail-recursive.


/Joe

On Fri, Aug 5, 2011 at 11:26 PM, Bob Cowdery <bob@REDACTED> wrote:
> Hi
>
> I'm wanting to interleave two binaries.
>
> Bin1 = <<0,1>>,
> Bin2 = <<2,3>>,
> << <<A,B,C,D>> || <<A,B>> <= Bin1, <<C,D>> <= Bin2 >>.
> <<0,1,2,3>>
>
> Bin1 = <<0,1,2,3>>,
> Bin2 = <<4,5,6,7>>,
> << <<A,B,C,D>> || <<A,B>> <= Bin1, <<C,D>> <= Bin2 >>.
> <<0,1,4,5,0,1,6,7,2,3,4,5,2,3,6,7>>
>
> whereas I want:
> <<0,1,4,5,2,3,6,7>>
>
> I know what it does is what the documentation says but is there a way to
> get a pure interleave efficiently. Perhaps there is a filter that would
> work or a way to reduce the binary after merging without stepping
> through the whole thing.
>
> Regards
> Bob
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list