0

I would like to apply a list of functions to an expression, like

ApplyList[{Re, Im}, Exp[I x]] = {Cos[x], Sin[x]}

How do I do that?

uranix
  • 537
  • 3
  • 14

4 Answers4

3

Version 10.1 includes ReIm which performs the operation you chose as your example. You'll need to add ComplexExpand to get the output you show:

ReIm[Exp[I x]] // ComplexExpand
{Cos[x], Sin[x]}

More generically you can make use of Map or Through. A complication arises if you are dealing with expressions which you do not want to evaluate prematurely. For that I propose:

SetAttributes[multiFn, HoldRest]

multiFn[fn_, args___] := Replace[fn, f_ :> f[args], {1}]

Now you can do things like:

multiFn[{Plus, Hold}, 2 + 2, 8/4]
{6, Hold[2 + 2, 8/4]}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2
thru1 = Assuming[Element[x, Reals], Simplify @ Through @ {Re, Im} @ ComplexExpand@#]&;

thru1 @ Exp[ I x]
(* {Cos[x], Sin[x]} *)

Or

thru2 = Composition[Assuming[Element[x, Reals], Simplify@#] &, 
                   Through@{Re, Im}@# &, ComplexExpand];

thru2 @ Exp[I x]
(* {Cos[x], Sin[x]} *)

Or

thru3 = Fold[#2[#] &, Exp[I x], 
     {ComplexExpand, Through@{Re, Im}@# &, Assuming[Element[x, Reals], Simplify@#] &}];

thru3 @ Exp[I x]
(* {Cos[x], Sin[x]} *)
kglr
  • 394,356
  • 18
  • 477
  • 896
1

This looks simpler than what has been proposed so far:

ApplyList = Through[#1[#2]] &;

ApplyList[{Re, Im}, Exp[I x]] // ComplexExpand
(*    {Cos[x], Sin[x]}    *)

Related: Best way to apply a list of functions to a list of values?

Roman
  • 47,322
  • 2
  • 55
  • 121
1
ApplyList[f_List, exp_] := Map[#1[exp] &, f]

However, without specifying if x is real, Mathematica will not output {Cos[x],Sin[x]}:

ApplyList[{Re, Im}, Exp[I x]]
Out= {Re[E^(I x)], Im[E^(I x)]}

ApplyList[{Re, Im}, Exp[I x]] // ExpToTrig // Simplify[#, Assumptions -> Element[x, Reals]] &
Out= {Cos[x], Sin[x]}