Passing a function as an argument of another function

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}]

Mathematica graphics

MultiSin[x_, y_] := Sin[x + y]/(Sqrt[x^2 + y^2])
MyPlot[MultiSin[x, 1], {x, 0, 1}]

Mathematica graphics

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}]

Mathematica graphics


If you really want the function to work like Plot, it also has to accept arguments that aren't explicitly functions, but simply expressions, such as x^2.

Here's how you do it:

Clear[MyPlot]

SyntaxInformation[MyPlot] = {"LocalVariables" -> {"Plot", {2, 2}}, 
   "ArgumentsPattern" -> {_, _, OptionsPattern[]}};
SetAttributes[MyPlot, HoldAll];

Options[MyPlot] = {};

MyPlot[f_, {x_, xmin_, xmax_}, opts : OptionsPattern[]] := 
 Module[{y, localF},
  localF = f /. x -> y;
  ListPlot[Table[{y, localF},
    {y, xmin, xmax, (xmax - xmin)/100}]
   ]
  ]

MyPlot[Sin[x], {x, 0, 1}]

MyPlot

What I did is to declare the HoldAll attribute so that the expression is passed along unevaluated, and moreover give some syntax information so that you get red typeface if you enter the arguments wrong. Then in the function, I localize the plot variable and call it y instead of the dummy argument x.

Tags:

Functions