More fun with APL

Note: see the rest of the series so far.

 

I stum­bled across this post the oth­er day and prob­lem 2 seems like some­thing I can eas­i­ly do in APL since it essen­tial­ly requires you to inter­leave two arrays.

The prob­lem is:

Write a func­tion that com­bines two lists by alter­nat­ing­ly tak­ing ele­ments. For exam­ple: giv­en the two lists [a, b, c] and [1, 2, 3], the func­tion should return [a, 1, b, 2, c, 3].

Here’s the solu­tion I have come up with:

p2

since it uses both \omega (right argu­ment) and \alpha (left argu­ment) so it’s a dyadic func­tion, let’s test it out:

'a' \ 'b' \ 'c' \ p2 \ 1 \ 2 \ 3

=> a 1 b 2 c 3

Here’s how it works:

  • con­cate­nate the two argu­ments togeth­er, with the left argu­ment first (\alpha, \omega)
  • reshape \rho the con­cate­nat­ed vec­tor into 2 rows, so that you have effec­tive­ly placed \alpha and \omega into a matrix, i.e.

a \ b \ c\\*    1 \ 2 \ 3

  • trans­pose that matrix

a \ 1\\*    b \ 2\\*    c \ 3

  • reshape \rho the trans­posed matrix into a vec­tor, and that’s it!