[erlang-questions] Interleave binaries
Hynek Vychodil
hynek@REDACTED
Sat Aug 6 10:06:36 CEST 2011
It would not be so much efficient because it would make stack for
every two bytes of input. Much more efficient will be
il(A, B) when is_binary(A), is_binary(B), size(A) =:= size(B) -> il(A, B, <<>>).
il(<<A:16,RestA/binary>>, <<B:16,RestB/binary>>, Acc) ->
Rest=il(RestA, RestB),
il(RestA, RestB, <<Acc/binary,A:16, B:16>>);
il(<<>>, <<>>, Acc) -> Acc.
See http://www.erlang.org/doc/efficiency_guide/binaryhandling.html#id64529
for more info about accumulator efficiency trick.
On Sat, Aug 6, 2011 at 6:40 AM, Wes James <comptekki@REDACTED> wrote:
> Hi,
>
> On Fri, Aug 5, 2011 at 3: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>>
>
> <snip>
>
> I don't know if this will suffice:
>
> -------------------------------------------------
>
> % interleave module
>
> -module(ilm).
>
> -export([il/2]).
>
> % interleave function
>
> il(<<A1,A2,RestA/binary>>, <<B1,B2,RestB/binary>>) ->
> Rest=il(RestA, RestB),
> <<A1, A2, B1, B2, Rest/binary>>;
>
> il(<<>>, <<>>) -> <<>>.
>
> -----------------------------------------------
>
> Erlang R14B02 (erts-5.8.3) [source] [smp:2:2] [rq:2] [async-threads:0]
> [hipe] [kernel-poll:false]
>
> Eshell V5.8.3 (abort with ^G)
> 1> c(ilm).
> {ok,ilm}
> 2> ilm:il(<<0,1,2,3>>, <<4,5,6,7>>).
> <<0,1,4,5,2,3,6,7>>
>
> ----------------------------------------------
>
> -wes
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
--
--Hynek (Pichi) Vychodil
Analyze your data in minutes. Share your insights instantly. Thrill
your boss. Be a data hero!
Try GoodData now for free: www.gooddata.com
More information about the erlang-questions
mailing list