Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Listable Attribute of Pure Function that returns a
Replies: 2   Last Post: May 8, 2013 4:10 AM

 Messages: [ Previous | Next ]
 lshifr@gmail.com Posts: 531 Registered: 2/9/09
Re: Listable Attribute of Pure Function that returns a
Posted: May 8, 2013 4:10 AM

On Tue, May 7, 2013 at 11:54 AM, Alex Krasnov <akrasnov@eecs.berkeley.edu>wrote:

>
>
>
> In my understanding, pure functions with anonymous parameters do not
> support attributes.

This is not true in principle, but you are right in that such form is not
documented. You have to use Null for the arguments:

Function[Null, #^2, Listable]

and this form also won't be syntax-highlihted properly by the Front End
(but will work).

> Pure functions with named parameters do as follows:
>
> In: Function[{a, b, c, d}, {{a, b}, {c, d}}, Listable][a, b, c,
> Array[d, 4]]
> Out: {{{a, b}, {c, d[1]}}, {{a, b}, {c, d[2]}}, {{a, b}, {c, d[3]}},
> {{a, b}, {c, d[4]}}}
>

> > If I do the same for a pure function that does not return a list,
> > everything is fine:
> >
> > In[42]:= ClearAll[func2]
> > SetAttributes[func2, Listable]
> > func2 = (#1 + #2)/(#3 - #4) &
> > func2[a, b, c, Array[d, 4]]
> >
> > Out[44]= (#1 + #2)/(#3 - #4) &
> >
> > Out[45]= {(a + b)/(c - d[1]), (a + b)/(c - d[2]), (a + b)/(
> > c - d[3]), (a + b)/(c - d[4])}
> >
> > And in any case, mathematica behaves the same here if I don't do
> > anything with the Attributes of func2, that is, there is no need to
> > explicitly SetAttributes to Listable for this particular example.

>
> In this case, func2 is not Listable, but Plus, Minus, Divide are.
>

In fact, making func2 Listable (for example using the constructs I
suggested above) would only make the function much slower in this
particular case. The reason is that in that case, it would thread over
lists using top-level evaluator, before handing the argument to its body.
While being just (#1 + #2)/(#3 - #4) &, it benefits from numerical
(built-in) listability of functions Plus, Times etc. Since this listability
is realized at a much lower level (kernel), it results in a much faster
execution.

Regards,
Leonid

>
> Alex
>
>

Date Subject Author
5/7/13 Alex Krasnov
5/8/13 lshifr@gmail.com