Erlang: how to implement an understanding of the Erlang list?

Implement an Erlang list comprehension that takes two items from a list and creates a new list of lists.

I have this code

pair([], Acc) -> lists:reverse(Acc); pair(L, Acc0) -> [ A, B | T ] = L, Acc = [ [A, B] | Acc0 ], pair(T, Acc). 

which works great:

 7> l:pair(lists:seq(1,6), []). [[1,2],[3,4],[5,6]] 

but it looks like I should implement this as a list comprehension. My Erlang-fu is too weak to come up with this.

Any suggestions?

thanks

+6
source share
2 answers

No, understanding a list would not be a good way to do this, by definition they only work with one item at a time. In your code there really is no need to use a battery, the difference in speed is small, here , and without it it becomes clearer. At least I think.

 pairs([A,B|L]) -> [[A,B]|pairs(L)]; pairs([]) -> []. 
+8
source

Understanding the list will be awkward because it inevitably has to do something for each element of the list. To create an understanding of the list, you should try to figure out if it is an odd or even element that you are talking to. Here is the idea of ​​what I'm talking about:

 pair(L) -> L2 = lists:zip(lists:seq(1, length(L)), L), [[A, B] || {Ai, A} <- L2, {Bi, B} <- L2, Ai rem 2 == 1, Bi rem 2 == 0, Ai + 1 == Bi]. 

The time complexity in this case is probably terrible, because, as far as I know, Erlang does not optimize it in any way.

I do not think that something is wrong with your function, and you should stick to it.

+1
source

Source: https://habr.com/ru/post/918702/


All Articles