How do I get the number of arguments passed to a function, such as Plus[2,3,4,5] has 4 arguments passed to it. I was thinking it may involve the use of the function Length and getting the arguments into a list. The intention is to iterate an operation based on the number of arguments for a function. There is probably a simple solution or function but I haven’t come across it yet. Any other ways or suggestions are welcome as well?
How do I get the number of arguments passed to a function, such as
Share
Here’s one way:
When you define a function like this, the pattern
args___(with 3 trailing underscores) will match aSequenceof 0 or more things. You can’t useLengthon aSequenceand have anything sensible happen, so you should wrapargsin aList(the{}) first.However, belisarius is correct. For a lot of iterative operations, it will be easier and more efficient to use built-in higher-order functions like
MapandFold.EDIT to add: Due to way that Mathematica expressions are built on top of bounds-checked arrays,
Lengthis O (1) in time. This might lead you to believe thatfooalso has O (1) complexity, but you would be wrong. Due to the way pattern-matching works, all of the elements matched byargswill be copied into the newListthat you then pass toLength, making the complexity O (N). This isn’t necessarily a huge problem, because using really huge argument lists with a function almost invariably means usingApply, which does an O (N) copy anyway, but it’s something you should know.EDIT again to add: There’s another way to do this using
Lengthdirectly on the expression being evaluated (like most of Mathematica’s list-oriented functions,Lengthcan be used on expressions with any head, not just lists). Nothing is copied because no sequences are matched and given new heads, and the function which is having its arguments counted need not have any special attributes likeHoldAll. Nonetheless, it is a sleazy hack that exploits a quirk in the pattern-matching machinery by introducing side-effects where side-effects really don’t belong, so I would use it with extreme caution, if at all:The variable
ncould be global, butModulewill create (or at least do a good job faking) lexical closures, so you can at least keep your variables local.