Possible Duplicate:
Pass function or formula as function parameter
I am trying to implement a simple Plot[]-like function, with the same synopsis; my first (and unique so far) try would be something along these lines:
MyPlot[f_, {var_, xmin_, xmax_}] := ListPlot[Table[{y, f[y]}, {y, xmin, xmax, (xmax - xmin)/100}]]
however I have to call the function as follows
MyPlot[Sin,{x,0,1}]
while I would prefer calling the function just like Plot[]
MyPlot[Sin[x],{x,0,1}]
I just don't know how to strip the "[x]" when a function is used as an argument to another function. This is not only a matter of consistency with Plot[], it is also needed in order to use a multi-argument function as the argument, such as:
MultiSin[x_,y_]:=Sin[x+y]/(Sqrt[x^2+y^2])
MyPlot[MultiSin[x,1],{x,0,1}]
which is not possible as far as I know with my simple re-implementation.
Answer
SetAttributes[MyPlot, HoldAll]
MyPlot[f_[a___, var_, b___], {var_, xmin_, xmax_}] :=
ListPlot[Table[{y, f[a, y, b]}, {y, xmin, xmax, (xmax - xmin)/100}]]
MyPlot[Sin[x], {x, 0, 1}]
MultiSin[x_, y_] := Sin[x + y]/(Sqrt[x^2 + y^2])
MyPlot[MultiSin[x, 1], {x, 0, 1}]
MultiMultiMultiSin[v_, x_, y_, z_] := Sin[x + y] Sin[x y z]/Sin[v]/(Sqrt[x^2 + y^2])
MyPlot[MultiMultiMultiSin[5, x, 2, 5], {x, 0, 1}]
Comments
Post a Comment