Passing a function to a module without specifying its arguments

I want to write

Module Arg[f_,n_] 

which takes a function f (having <= n arguments) and a positive integer n and prints the nth argument of f.

As an example, suppose that f is defined

 f[a_,b_]=a^2+b^2. 

Then

 Arg[f[s,t],1] 

must be s;

while

 Arg[f[u,v],2] 

must be v.

My question is whether this is possible. If so, what should I write instead of "???" below?

 Arg[f_,n_] := Module[{}, ??? ] 

Note that I do not want to specify a_ and b_ in the definition of Arg as

  Arg[f_,a_,b_,n_] 

EDIT: "Arg" is just my name for the module, not the internal function of Arg Mathematica.

+6
source share
2 answers

Can

 SetAttributes[arg, HoldFirst]; arg[f_[x___], n_] := {x}[[n]] f[a_, b_] := a^2 + b^2. arg[f[arg[f[s, t], 1], t], 1] arg[f[s, t], 2] (* -> s -> t *) arg[ArcTan[f[ Cos@Sin @x, x], t], 1] (* -> x^2. + Cos[Sin[x]]^2 *) 
+10
source

Assuming your second example should give u , this should do the job:

 ClearAll[arg]; SetAttributes[arg, HoldFirst]; arg[g_, n_] := Module[ {tmp, ret}, Unprotect[Part]; tmp = Attributes[Part]; SetAttributes[Part, HoldFirst]; ret = Part[g, n]; ClearAttributes[Part, HoldFirst]; SetAttributes[Part, tmp]; Protect[Part]; ret ] 

so that

 f[a_, b_] = a^2 + b^2.; arg[f[s, t], 1] 

gives s .

This is very difficult, so I expect someone to find something better soon.

This is slightly better (does not override built-in functions even temporarily):

 ClearAll[arg2]; SetAttributes[arg2, HoldFirst]; arg2[g_, n_] := Hold[g][[1, n]] 
+4
source

Source: https://habr.com/ru/post/901912/


All Articles