3

What I need is the equivalent of Maple's zip(+, A, B, 0). Sure I can get it with:

Thread[PadRight[A, max = Max[Length[A], Length[B]]] + PadRight[B, max]]

But is there a less verbose way to do this?

P.S. Eventually the shortest solution seems to be:

 Plus @@ PadRight[{A, B}]
user6109
  • 61
  • 2

2 Answers2

8
a = {1, 2, 3};
b = {q, r, s, t, u};
Plus @@@ Flatten[{a, b}, {2}]
{1 + q, 2 + r, 3 + s, t, u}

See: Flatten command: matrix as second argument

For convenience:

SetAttributes[myThread, HoldFirst]
myThread[h_[args__]] := h @@@ Flatten[{args}, {2}]

Now:

myThread[a + b]
{1 + q, 2 + r, 3 + s, t, u}

This utility may also be useful.


The reason I showed use of Flatten rather than PadRight is that it is more general. With PadRight your function will see zeros:

Times @@ PadRight[{a, b}]
{q, 2 r, 3 s, 0, 0}

Compare to:

myThread[a*b]
{q, 2 r, 3 s, t, u}

Of course for Times you could pad with ones, but the point is that the padding element would have to be changed to match the function, and for some functions no padding element would be correct.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
-1

Another possibility, which I cannot judge as equivalent to Maple's zip, is to use Distribute:

a = {1, 2, 3};
b = {q, r, s, t, u};

Distribute[f[a, b], List]

{f(1,q),f(1,r),f(1,s),f(1,t),f(1,u),f(2,q),f(2,r),f(2,s),f(2,t),f(2,u),f(3,q),f(3,r),f(3,s),f(3,t),f(3,u)}

If f is List, the result is:

Distribute[{a, b}, List]

{{1, q}, {1, r}, {1, s}, {1, t}, {1, u}, {2, q}, {2, r}, {2, s}, {2, t}, {2, u}, {3, q}, {3, r}, {3, s}, {3, t}, {3, u}}

user8074
  • 1,592
  • 8
  • 7