MathGroup Archive 2009

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

Search the Archive

on passing arguments to a function, how to break a list into separate items during a call?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg103701] on passing arguments to a function, how to break a list into separate items during a call?
  • From: "Nasser Abbasi" <nma at 12000.org>
  • Date: Sat, 3 Oct 2009 09:01:20 -0400 (EDT)
  • Reply-to: "Nasser Abbasi" <nma at 12000.org>

Suppose there is a function foo[] which returns back 2 items, say 'i' and 
'j'. They must be returned as a list ofcourse, so we have this

foo[] := Module[{i, j},
     i = 3;
     j = 7;
    {i, j}
]

Now I have another function goo[] which accepts 2 items as input, and does 
something with them, as in

goo[i_, j_] := Module[{},
         i + j
]

Now I'd like to call foo[], and take its output, and pass it to directly to 
goo[], but I can NOT do the following:

                             goo[foo[]]

because there is no function goo[] which accept a list defined. I could 
solve this easily by making an intermediate step

{i, j} = foo[];   (*first read into local variables*)
goo[i, j]    (* then call goo[] *)

I tried to see if it is possible to eliminate this intermediate step, as it 
could be unnecessary, and see if there is a function or a trick in 
Mathematica which takes a list and 'unwrap' it for the purpose of making 
function calls.

Assuming such a function or method, lets call it  'W' for now, then I would 
just type

                             goo[ W[foo[]] ]

Where W[] would take output from a function, and if it is a list, would 
break it down to its sublists, so  that goo[ W[foo[]] ] would be converted 
to  goo[ i,j ].  This W[] function would only ofcourse work in the context 
of function calls, as it does not make sense to write

W[{1,2}] and expect to get just  "1,2" like this, without these being 
grouped in a List[]. So this function W is means only to work in argument 
passing.

I can also solve this easily by making goo[] accepts a list, but I wanted to 
avoid having to type this:

goo[arg_List] := Module[{},
            arg[[1]] + arg[[2]]
]

I think   writing "i+j" is more clear than writing " arg[[1]] + arg[[2]]", 
that is why I am asking this question.

I wish Mathematica has named arguments?  or structs, so I could write

goo[arg_Struct] := Module[{},
            arg.i + arg.j
]


Any ideas?

Thank you,
--Nasser




__________ Information from ESET NOD32 Antivirus, version of virus signature database 4476 (20091002) __________

The message was checked by ESET NOD32 Antivirus.

http://www.eset.com





  • Prev by Date: Re: Re: Making raw HTML appear in a notebook exported to
  • Next by Date: Re: Re: Making raw HTML appear in a notebook exported to
  • Previous by thread: Re: Re: Mouse-Over or Mouse-Click Values of Coordinates in
  • Next by thread: Re: on passing arguments to a function, how to break a