1
$\begingroup$

I wish to define a function, which accepts either functions or constants as arguments. I tried

g[t_, y_] := Module[{}, t[y]]

which simply evaluates some function t at y.

Now if I run

t[x_] = 300
g[t, y]

the module g simply returns 300. However if I run

g[300, y]

it returns:

300[y] 

How do I define g in such a way that it accepts either functions or constants as arguments?

$\endgroup$
2
$\begingroup$

Edited

I'm uncomfortable with the idea of writing a function with the kind of special behavior you propose, but if I had to, I would implement it this way.

g[x_?NumericQ, y_] := x
g[t_, y_] := t[y]

Then

Clear[t]; t[x_] = 300; g[t, y]

300

Clear[h]; h[x_] := 3 x; g[h, y]

3 y

g[300, y]

300

g[#^2 &, y]

y^2

$\endgroup$
  • $\begingroup$ +1, but I think in this case less might even be more. If you don't restrict the first pattern to _Symbol | _Function it will also work for other function like arguments like e.g. CompiledFunction, InterpolatingFunction, ParametricFunction, FittedModel... $\endgroup$ – Albert Retey Jul 2 '17 at 15:21
  • $\begingroup$ @AlbertRetey. You're right, and I have edited the answer accordingly. $\endgroup$ – m_goldberg Jul 2 '17 at 15:48
0
$\begingroup$
SetAttributes[g, Orderless]
g[t_Symbol, y_] := Module[{}, t[y]]

g[t, 200]

t[200]

g[300, y]

y[300]

t[x_] := 300
g[300, t]

300

g[t, 200]

300

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.