8
$\begingroup$

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]} & *)
$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Rojo Aug 24 '13 at 18:24
8
$\begingroup$

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.

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

 With[{f = Function[t, Cos[t]]},
  With[{k = f'[#]}, {First@#, k} &]
 ]
$\endgroup$
0
$\begingroup$
With[{f = Function[t, Cos[t]]}, {First[#] &, f'[#] &}][[2]]

Put the & inside the bracket for each function instead.

$\endgroup$
  • $\begingroup$ Thanks, but this is not exactly what I mean. $\endgroup$ – mmal Aug 24 '13 at 15:51

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.