count - Mathematica: get number of arguments passed to a function? -


How do I get the number of arguments passed to a function, such as plus [2,3,4, 5] There are 4 arguments in it I was thinking that the length of the function and the logic can be included in a list. Intention is to repeat the operation based on the number of arguments for a function. Probably a simple solution or work, but I have not crossed it yet. Any other ways or suggestions are also welcome?

Here's a way:

 In  [1]: = Foo [args ___]: = length [{args}] in [2]: = foo [1,2,3,4] outside [2] = 4  

Define a function, the pattern args ___ (with 3 underscores underscores) will match 0 or more things. You can not use the length on length and anything is intelligent, so you have args in the list Should be wrapped> ( {} ) first.

However, belisarius is right. For many overridden tasks, using built-in high-order functions such as map and fold will be easier and more efficient.

Edit to add: The way mathematical expressions are created at the top of the bound-check array, in time length is O (1) This can convince you that (1) has complexity, but you will be wrong . Due to pattern-matching actions, all elements matched with args will be shown copied in the new list , then you Creating complexity O ( N ) is not necessarily a big problem, because the function actually contains very large logic lists Is almost always used to use apply , which O ( N does it)> any type of antithesis Create party, but you should know something.

Edit again to add: Another method of using length directly on this expression is being evaluated (Most Mathematica The list-oriented function, length can be used on expression with any head, not just lists). Nothing has been copied because no sequence is matched and new heads are given, and the function in which its arguments are counted does not require any special features like holdel . However, this is a random hack that uses a side effect in pattern-matching machinery, in which side-effects start, where side-effects are not actually, so I will use it with utmost care, if Exactly:

Module [{n}, expr: foo [___] /; (N = length [unchanged [expr]]; true): = n]

variable n may be global, but module (Or at least a good job) will close the syntax, so that you can at least make your variable local.


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -