views:

43

answers:

2

Hi Everyone,

So this I just had one problem solved very quickly by a nice guy on my other post.

http://stackoverflow.com/questions/3464207/erlang-splitting-lists-into-sub-list

Now I am a beginner at Erlang and need a little help with the syntax of another function that does work on the result from my previous post.

For example, I now have:

   Reply = [<<56,45,34,07,45,67,34>>, <<12,23,56,07,67,67>>,  <<55,23,45,07,89,56>>]

And I need to split it further to:

[ [<<56,45,34>>,<<45,67,34>>], [<<12,23,56>>,<<67,67>>] ,  [<<55,23,45>>, <<89,56>>]  ]

The delimiter in this example is <<07>>

This code process's the binary

parse(Reply) -> binary:split(Reply, <<07>>, [global]).

But now how can I recursively go through the array and do it again.

Here is an example of my current code:

parse(Reply) -> binary:split(Reply, <<01>>, [global]).
parse2(Reply) -> binary:split(Reply, <<07>>, [global]).

func1(Done) -> [parse2(X) || X <- Done].

%%blah blah - get to the executing functions code
Done = parse(Reply),
Done1 = func1(Done),

I know it has to be something super simple the last one sure had me.

Best, -B

A: 

Figured it out please feel free to let me know if there is a more efficient way - or - just your way, I am learning after all.

parse(Reply) -> binary:split(Reply, <<01>>, [global]).
parse2(<<>>) -> <<>>;
parse2(Reply) -> binary:split(Reply, <<"=">>, [global]).

func2([H|T], Result) ->
    H1 = parse2(H), 
    func2(T, [H1|Result]);
func2([], Result) -> io:format("Reply 1 = ~p~n", [Result]), Result.


Done = parse(Reply),

Done1 = func2(Done, []),

-B

+1  A: 

Use a list comprehensions to apply a function to every element of a list. The function is pretty much the same as for your last question:

1> L = [<<56,45,34,07,45,67,34>>, <<12,23,56,07,67,67>>,  <<55,23,45,07,89,56>>].
[<<56,45,34,7,45,67,34>>,
 <<12,23,56,7,67,67>>,
 <<55,23,45,7,89,56>>]
2> [binary:split(X, <<07>>, [global]) || X <- L].
[[<<"8-\"">>,<<"-C\"">>],
 [<<12,23,56>>,<<"CC">>],
 [<<55,23,45>>,<<"Y8">>]]
3> io:format("~w~n",[[binary:split(X, <<07>>, [global]) || X <- L]]).
[[<<56,45,34>>,<<45,67,34>>],[<<12,23,56>>,<<67,67>>],[<<55,23,45>>,<<89,56>>]]
ok

Another option is to use lists:map/2:

4> lists:map(fun(X) -> binary:split(X, <<07>>, [global]) end, L).
[[<<"8-\"">>,<<"-C\"">>],
 [<<12,23,56>>,<<"CC">>],
 [<<55,23,45>>,<<"Y8">>]]
I GIVE TERRIBLE ADVICE