1

I'm trying to pass a function of a variable (t) into a module where I will do lots of manipulation (such as taking the derivitave). But I'm not sure what the right way is. I have a workaround (f2), but it doesn't seem like the right way. What's the best practice in this case? thanks!

f[t_] = t^2;

function[f_] := Module[{},
 f1[t_] = f;
 f2[t2_] = f /. t -> t2;

 Print["f[2] = ", f[2]];
 Print["f/.t->2 = ", f /. t -> 2];
 Print["f1[2] = ", f1[2]];
 Print["f2[2] = ", f2[2]];

 Print["f'[2] = ", f'[2]];
 Print["f1'[2] = ", f1'[2]];
 Print["f2'[2] = ", f2'[2]];
];


 function[f[t]]
f[2] = (t^2)[2]

f/.t->2 = 4

f1[2] = t^2

f2[2] = 4

f'[2] = ((t^2)')[2]

f1'[2] = 0

f2'[2] = 4

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574

1 Answers1

2

Define f with SetDelayed ( := ) rather than Set ( = ), and pass it by name as you would a built-in function. It will perform just like a built-in function.

f[t_] := t^2
g[h_] :=
  Block[{df, t},
   df[t_] = h'[t];
   Integrate[df[t], t]]
g[f]

t^2

g[1 + Sin[#]^2 &]

-(1/2) Cos[2 t]

This result is correct because it differs from 1 + Sin[t]^2 only by a constant.

Simplify[-(1/2) Cos[2 t] - Sin[t]^2]

-1/2

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
  • Thank you for the response. Unfortunately, f[t] is defined earlier in the code (sometimes it is an interpolated function) and comes in as a Set (=). – samuel Schweighart Aug 14 '16 at 19:13
  • @samuelSchweighart. The remark about Set and SetDelay apply to your definition for f, not in general. The remark about passing the function in by name holds generally. But look at the 2nd example. The function passed in there wasn't defined with either Set or SetDelayed and it still works. – m_goldberg Aug 14 '16 at 19:41