Suppose we're given the expression f*g+h
, where f,g,h
are all pure functions. How can we evaluate this expression on some x
? If there were only one operation, say f+g
, we could simply use Through[(f+g)[x]]
, but Through
only deals with one operation, as far as I can see. How is this done?
Answer
Edit:
Mr.Wizard helped to refine my old function to:
SetAttributes[Through2, HoldFirst]
Through2[head_[args___]] := Replace[head, s : _Function | _Symbol :> s[args], -1]
This locates the most nested functions and symbols and evaluates their value for the parameter arguments.
Below is my older, less robust function:
SetAttributes[Through2, HoldFirst]
Through2[expr_] :=
With[{head = Head@expr, arg = First@expr},
With[{funcs = Cases[head, _Function | _Symbol, -1]},
head /. Thread[funcs -> Through[funcs[arg]]]]]
Through2[(f*g + h)[x]]
(* f[x] g[x] + h[x] *)
Through2[(f*g + (h*Minus)^2)[x]]
(* f[x] g[x] + x^2 h[x]^2 *)
Through2[{Re, Im + Re}[x]]
(* {Re[x], Im[x] + Re[x]} *)
Comments
Post a Comment