Re: Destructuring arguments to pure functions?
- To: mathgroup at smc.vnet.net
- Subject: [mg94902] Re: Destructuring arguments to pure functions?
- From: Jens-Peer Kuska <kuska at informatik.uni-leipzig.de>
- Date: Tue, 30 Dec 2008 05:52:16 -0500 (EST)
- References: <gjad0c$p4b$1@smc.vnet.net>
Hi,
Map[Total, testList]
Plus @@@ testList
Map[(Plus @@ #) &, testList]
and
myplus = Compile[{{lst, _Integer, 1}}, Plus @@ lst];
Map[myplus, testList]
??
On my machine the last two are faster than your Example 5.
Regards
Jens
Stoney Ballard wrote:
> I hate using #[[1]] etc. to access elements of list arguments to pure
> functions, so I've been looking for a way around that.
>
> One way is to simply stop using pure functions in those cases, and use
> locally bound function definitions, like
>
> testList = Flatten[Table[{x, y}, {x, 1, 100}, {y, 1, 100}], 1];
>
> (Example 1)
>
> Module[{fun},
> fun[{x_, y_}] := x + y;
> Map[fun, testList]]
>
> This turns out to be significantly faster than any other method I've
> tried, but it seems clunky and requires Module.
>
> Another way is to use RuleDelayed:
>
> (Example 2)
>
> Map[# /. {x_, y_} :> x + y &, testList]
>
> but this is about 5 times slower than example 1. Binding the rule with
> Module:
>
> (Example 3)
>
> Module[{fun = {x_, y_} :> x + y},
> Map[# /. fun &, testList]]
>
> Is only marginally slower than example 1, but still requires Module or
> With. Strangely (to me), I found that binding the rule as a pure
> function:
>
> (Example 4)
>
> Module[{fun = # /. {x_, y_} :> x + y &},
> Map[fun, testList]]
>
> is about the same speed as example 2, or 5 times slower than example
> 1. I don't understand why there should be so much of a difference
> there.
>
> Finally, doing this with Part:
>
> (Example 5)
>
> Map[#[[1]] + #[[2]] &, testList]
>
> is 2-3 times faster than using destructuring in example 1.
>
> Clearly, I need to give up some performance to get the clarity of
> destructuring, but is there a better way than example 1?
>
>