1
$\begingroup$

The behavior of Listable vector functions is weird, the output of the code below for me was {{2, 6, 12}, {1, 8, 27}} and {f[1, 1, 1], f[2, 2, 2], f[3, 3, 3]}. From the second output I would expect a list with 3 sub lists for the first, but you don't get that. Is it supposed to work like that or is it a bug? (I know that taking the transpose of output 1 I get the output 2 format, but I have functions with higher rank tensors, which makes it hard to keep track of these transposes)

f =Function[{x,y,z}, {x*y+z, z^2*x}  ];
SetAttributes[f,Listable]
f[ {1,2,3},{1,2,3},{1,2,3}]
Clear@f;
SetAttributes[f,Listable];
f[ {1,2,3},{1,2,3},{1,2,3}]```
$\endgroup$
1
  • 2
    $\begingroup$ Use Function[..., Listable] instead, as the listabile attribute is not getting invoked. The head is evaluated before that listability attribute is applied, and once the head gets replaced with the Function object, the listability of f is not relevant. $\endgroup$
    – Carl Woll
    Commented Jan 11 at 18:56

1 Answer 1

2
$\begingroup$

The Listable has no effect when you use f this way. f gets immediately replaced with the Function expression (heads are evaluated before arguments), and Function is not Listable. And arithmetic functions are designed to work with lists (and are Listable). So consider,

in1 = {a, b, c};
in2 = {m, n, o};
in3 = {x, y, z};
{in1*in2 + in3, in3^2*in1}

(* {{a*m + x, b*n + y, c*o + z}, {a*x^2, b*y^2, c*z^2}} *)

This is the same as you get from the Function you assigned to f.

Contrast that with these:

SetAttributes[g, Listable];
g[x_, y_, z_] := {x*y + z, z^2*x};
g[in1, in2, in3]

(* {{a*m + x, a*x^2}, {b*n + y, b*y^2}, {c*o + z, c*z^2}} *)

h = Function[{x, y, z}, {x*y + z, z^2*x}, Listable];
h[in1, in2, in3]

(* {{a*m + x, a*x^2}, {b*n + y, b*y^2}, {c*o + z, c*z^2}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.