wolfram-mathematica

Function as parameter for Module


How is it possible to use a mathematical function as module- parameter

Such as:

PersonalPlot[fun0_, var0_, min0_, max0_] :=
 Module[{fun = fun0, var = var0 , min = min0, max = max0},

   (*this is incorrect*)
   fun = fun[var_];

   Plot[fun, {var, min, max}]
 ]

PersonalPlot[x^2,x,0,3];

Solution

  • You're right, that statement is incorrect. Mathematica evaluates it to something like

    x^2[x]
    

    when you call PersonalPlot and that evaluates to, well, in words to x to the power of 2 of x which doesn't make a lot of sense. There are a number of ways round the problem. The simplest would be to dispense with a Module altogether and define:

    PersonalPlot1[fun0_, var0_, min0_, max0_] := Plot[fun0, {var0, min0, max0}]
    

    which you would call like this:

    PersonalPlot1[x^2, x, 0, 3]
    

    Note that a call like this PersonalPlot1[x^2, y, 0, 3] produces an empty plot because the variable in the function passed in is not the same variable as the second argument. Read on.

    If you want to define a module which takes a function as an argument, then this is one way of doing it:

    PersonalPlot2[fun0_, var0_, min0_, max0_] := 
     Module[{fun = fun0, var = var0, min = min0, max = max0},
      Plot[fun[var], {var, min, max}]]
    

    which you would call like this

    PersonalPlot2[#^2 &, x, 0, 3]
    

    Note:

    Another possibility would be to drop the argument which represents the variable input to the function passed to PersonalPlot, like this:

    PersonalPlot3[fun0_, min0_, max0_] := Module[{x},
      Plot[fun0[x], {x, min0, max0}]]
    

    which you would call like this

    PersonalPlot3[#^2 &, 0, 3]
    

    In this version I've made x local to the Module to avoid clashes with any workspace variable also called x. This avoids errors arising from using different names for the argument to the function (the pure function has no argument names) and the second argument to PersonalPlot; that has now been dropped.

    There are probably several other useful ways of passing arguments to functions whether those functions use modules or not.

    EDIT

    Most of us who've used Mathematica for a while don't, I think, regard #^2& as something to avoid. If you don't like it, you could use the more explicit syntax, like this:

    fun1 = Function[x,x^2]
    

    which you can then pass around like this

    PersonalPlot[fun1,0.0,4.0]
    

    By using this approach you can make your functions a bit less error prone by requiring the right types to be passed in, like this

    PersonalPlot[fun_Function, min_Real, max_Real] := ...
    

    but it's really up to you.

    Off the top of my head I don't know how Plot does it, I'd have to look in the documentation.