5

Is it possible to use list comprehension on two lists, item by item, in sequence? Given A = [1,2,3], B = [4,5,6], get some C = [f(1, 4), f(2, 5), f(3, 6)]. In other words, a more direct/efficient way to do [f(U, V) || {U, V} = lists:zip(A, B)].

Similar question goes to binaries, if given A = <<1,2,3>> and B = <<4,5,6>>. This would be very useful if you have to xor two binaries, for example.

hlovdal
  • 26,565
  • 10
  • 94
  • 165
me2
  • 3,069
  • 2
  • 26
  • 33

2 Answers2

8

It's not currently possible. It has already been proposed in EEP12 and EEP19.

Your best choice is to implement your own recursive function for that.

Community
  • 1
  • 1
Zed
  • 57,028
  • 9
  • 76
  • 100
3

There is already a higher-order-function in the lists module for this and it is called lists:zipwith/3. Your example scenario would be implemented this way:

lists:zipwith(fun f/2, A, B).
Christian
  • 9,417
  • 1
  • 39
  • 48
  • Yes, there are functions for zipping two or three lists. But there is no general solution for N lists, as a list comprehension would be. – Zed Dec 19 '09 at 18:59