Search code examples
pass-by-referencemaple

Maple passing parameters by reference


I know that in Maple the way of passing arguments is always by value, so i'm wondering if there is a way to pass parameters by reference in a Maple procedure. I've read something about the REF identifier but i have not understood very well.. Someone that knows something about it?


Solution

  • That REF you mentioned is very likely just the qualifier around parameters in a `define_external, used to link to compiled functions outside of Maple's kernel and interpreted library. It does not provide pass-by-reference in a broader sense, for Maple procedures.

    In Maple rtables (Matrix, Vector, Array) and tables are passed by reference, allowing for in-place semantics on these mutable structures.

    Otherwise arguments to procedure calls are mostly done by value. That is, the value of the passed name (variable). In Maple's normal evaluation rules for procedure calls, passed names are evaluated up front, and their values become the procedure arguments.

    But if the name is passed within unevaluation quotes (single right-quotes) then the argument is just the name, rather than its value. So then that name is available within the procedure call. And the procedure can even assign to that name (producing a side effect). Or the procedure can do another evaluation, to get at the value. So, in this scenario, the parameter is being passed-by-name, which is pass by reference in a way.

    Other ways to get the same effect involve constructing the procedure definition so that parameters are passed by name rather than value. In such a case no extra unevaluation quotes are needed when the procedure is called.

    Notice how p1 and p2 are called differently, below. You can also experiment with what happens (various error messages) if you call them with different kinds of argument.

    p1 := proc( x )
            local y;
            y := eval(x);
            print( x, y );
            x := y^2;
            return NULL;
          end proc:
    
    m := 4;
                                   m := 4
    
    p1( 'm' );
                                    m, 4
    
    m;
                                     16
    
    p2 := proc( x::uneval )
            local y;
            y := eval(x);
            print( x, y );
            x := y^2;
            return NULL;
          end proc:
    
    m := 4;
                                  m := 4
    
    p2( m );
                                   m, 4
    
    m;
                                     16