8

The question concerns creating a function. Let consider the following code

With[{f = Function[t, Cos[t]]},
 {First[#], f'[#]} &
]

which returns

(* ==> {First[#1], Function[t, Cos[t]]'[#1]} & *)

How to can I force it to return the derivative evaluated (only second part of the returned list); i.e., how to can I get

(* ==> {First[#1], -Sin[#1]} & *)
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
mmal
  • 3,508
  • 2
  • 18
  • 38
  • As halirutan said, you want to build a function with a part of it already evaluated. Not all of it, or First@# would be evaluated and you don't want that. So, you want to inject code into a held expression. Search for that in the site. – Rojo Aug 24 '13 at 18:24

3 Answers3

8

Function, and in your case the syntactic sugar with # you are using, holds its arguments. Therefore, your expression is not evaluated. There are several ways to do this and I'm sure they were already discussed here, but I cannot find the question now. Anyway, one way is to use replacements

With[{f = Function[t, Cos[t]]},
 Block[{expr},
  {First[#], expr} & /. expr -> f'[#]
  ]
]

another one is to use yet another pure function

With[{f = Function[t, Cos[t]]},
 Function[expr, {First[#], expr} &][f'[#]]]

Additionally, this Q&A discusses the issue too and gives more thourough explanations in the answers.

halirutan
  • 112,764
  • 7
  • 263
  • 474
  • What about named formal parameters instead of # (there is a possibility there where renamed before function construction)? – mmal Aug 24 '13 at 22:16
4
With[{f = Function[t, Cos[t]]},
  Evaluate[{First[k], f'[k]}] & /. k :> # // Quiet
 ]

 With[{f = Function[t, Cos[t]]},
  With[{k = f'[#]}, {First@#, k} &]
 ]
chyanog
  • 15,542
  • 3
  • 40
  • 78
0
With[{f = Function[t, Cos[t]]}, {First[#] &, f'[#] &}][[2]]

Put the & inside the bracket for each function instead.

Frank
  • 121
  • 5