MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Destructuring arguments to pure functions?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg94921] Re: [mg94881] Destructuring arguments to pure functions?
  • From: Bob Hanlon <hanlonr at cox.net>
  • Date: Tue, 30 Dec 2008 05:55:43 -0500 (EST)
  • Reply-to: hanlonr at cox.net

You can also just use Plus or Total

testList = Flatten[Table[{x, y},
    {x, 1, 1000}, {y, 1, 1000}], 1];

r1 = Module[{fun}, fun[{x_, y_}] := x + y;
    Map[fun, testList]]; // Timing

{1.84311,Null}

r2 = Map[# /. {x_, y_} :> x + y &, testList]; // Timing

{6.95226,Null}

r3 = Module[{fun = {x_, y_} :> x + y},
    Map[# /. fun &, testList]]; // Timing

{2.34573,Null}

r4 = Module[{fun = # /. {x_, y_} :> x + y &},
    Map[fun, testList]]; // Timing

{6.93115,Null}

r5 = Map[#[[1]] + #[[2]] &, testList]; // Timing

{0.441319,Null}

r6 = Plus @@@ testList; // Timing

{0.776652,Null}

r7 = Total /@ testList; // Timing

{1.16141,Null}

r1 == r2 == r3 == r4 == r5 == r6 == r7

True


Bob Hanlon

---- Stoney Ballard <stoneyb at gmail.com> 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?



  • Prev by Date: Re: numerical fourier transforms
  • Next by Date: Re: Undo and redo
  • Previous by thread: Re: Destructuring arguments to pure functions?
  • Next by thread: Re: numerical fourier transforms