Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

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

Search the Archive

Re: Map[] and multiple args function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg96230] Re: [mg96198] Map[] and multiple args function
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Tue, 10 Feb 2009 05:47:36 -0500 (EST)
  • References: <200902091033.FAA12309@smc.vnet.net>

On Feb 9, 2009, at 5:33 AM, sagrailo at gmail.com wrote:

> I know this has to be FAQ, but I'm just not able to find an answer
> anywhere, so - here it goes:  I have a multiple-arguments function,
> say something like:
>    Foo[x_, y_, z_] := x + 2*y + 3*z
> Now, I want to call this function number of times, over different sets
> of arguments, and then to sum results.  I thought about storing
> argument triplets into some kind of list, and then employing sequence
> of Map[] and Apply[] to get the job done.  After number of trials and
> errors, I came up with following piece of code doing the thing:
>   Plus @@ Foo /@ {{1, 2, 3}, {4, 5, 6}} /. List -> Sequence
> but I even don't fully understand what's going here, and also I'm
> wondering is there a "better" way to accomplish this.  So - any
> suggestion?

Writing your code out longhand would help with interpretation,  
longhand it's:

ReplaceAll[Apply[Plus, Map[Foo, List[List[1, 2, 3], List[4, 5, 6]]]],
  Rule[List, Sequence]]

(obtained doing FullForm[Hold[Plus @@ Foo /@ {{1, 2, 3}, {4, 5,  
6}} /. List -> Sequence]])

So the first thing that happens is Foo is mapped onto {{1, 2, 3}, {4,  
5, 6}} giving

{Foo[{1, 2, 3}], Foo[{4, 5, 6}]}

Plus is applied giving:

Foo[{1, 2, 3}],+Foo[{4, 5, 6}]

then the lists are replaced by sequences leading to the evaluation of:

Foo[1, 2, 3],+Foo[4, 5, 6]

You can avoid the replace by applying Foo directly to the appropriate  
level of the argument list, either using the shorthand

Plus@@Foo@@@{{1,2,3},{4,5,6}}

or

Apply[Plus,Apply[Foo,{{1,2,3},{4,5,6}},{1}]]


  • Prev by Date: Re: Map[] and multiple args function
  • Next by Date: Re: FindFit & NIntegrate
  • Previous by thread: Map[] and multiple args function
  • Next by thread: Re: Map[] and multiple args function