Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2004
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

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

Search the Archive

Re: List arguments to functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg45575] Re: List arguments to functions
  • From: "Peter Pein" <nospam at spam.no>
  • Date: Wed, 14 Jan 2004 01:26:41 -0500 (EST)
  • References: <bu0cnm$aib$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

"Chris Rozell" <crozell at rice.edu> schrieb im Newsbeitrag
news:bu0cnm$aib$1 at smc.vnet.net...
> I have basic experience with Mathematica, but this problem has stumped
> me for the last day or so.  Any help would be appreciated.
>
> I have a function that needs to take two lists as arguments, perform
> operations on them, and then sum the resulting list.  However, by
> including the Plus function, it operates on each list item separately
> (which is exactly the opposite of what I need.  For a simple example,
>
>  >myfunc[x_, y_] = Apply[Plus, x + y];
>  >myfunc[{1, 2, 3}, {4, 5, 6}]
>  >
>  >{5, 7, 9}
>
> When what I would really like is the number 21 (i.e., 5+7+9, perform the
> list addition first, then sum the components).  In this simple example I
> could perform the summation after the function returns, but in my real
> problem this would not be possible.
>
> When reading the documentation, it appears that the Plus function
> behaves this way because it has the attribute "Flat".  But even after
> removing that attribute it still behaves in the same way, so I may be
> misunderstanding the description of "flat".  Can anyone suggest a way to
> either modify the Plus function behavior, or do this another way?  Thank
> you in advance!
>

Chris,
you use Set (=) instead of SetDelayed (:=) in the definition of myfunc. So
Mathematica evaluates Apply[Plus,x+y], which gives x+y before defining
myfunc. If you use :=, Mathematica evaluates Apply[Plus,x+y] when executing
the call to myfunc:

In[1]:=
myfunc[x_, y_] = Plus @@ (x + y);
?? myfunc

Global`myfunc
myfunc[x_, y_] = x + y

In[3]:=
Clear[myfunc];
myfunc[x_, y_] := Plus @@ (x + y);
?? myfunc

Global`myfunc
myfunc[x_, y_] := Plus @@ (x + y)

In[6]:=
myfunc[{1, 2, 3}, {4, 5, 6}]

Out[6]=
21

--
Peter Pein, Berlin
petsie at arcAND.de
replace && by || to write to me
"The ultimate goal of mathematics is to eliminate any need for intelligent
thought."
-Alfred N. Whitehead



  • Prev by Date: Re: what is the general theory of extracting solutions from DSolve (and similar) functions
  • Next by Date: RE: List arguments to functions - Use of Inner Command
  • Previous by thread: Re: List arguments to functions
  • Next by thread: what is the general theory of extracting solutions from DSolve (and similar) functions