Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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]} & *)
share|improve this question
    
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 Answers 3

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.

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

 With[{f = Function[t, Cos[t]]},
  With[{k = f'[#]}, {First@#, k} &]
 ]
share|improve this answer
With[{f = Function[t, Cos[t]]}, {First[#] &, f'[#] &}][[2]]

Put the & inside the bracket for each function instead.

share|improve this answer
    
Thanks, but this is not exactly what I mean. –  mmal Aug 24 '13 at 15:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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