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?
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?
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]}
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]} *)
TargetFunctions option of ComplexExpand[] is useful, too.
– J. M.'s missing motivation
May 18 '15 at 08:42
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?
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]}
Through[]? – J. M.'s missing motivation May 18 '15 at 08:21