Go to the first, previous, next, last section, table of contents.

Function Definition

Introduction to Function Definition


To define a function in Maxima you use the := operator. E.g.

f(x) := sin(x)

defines a function f. Anonmyous functions may also be created using lambda. For example

lambda ([i, j], ...)

can be used instead of f where

f(i,j) := block ([], ...);
map (lambda ([i], i+1), l)

would return a list with 1 added to each term.

You may also define a function with a variable number of arguments, by having a final argument which is assigned to a list of the extra arguments:

(%i1) f ([u]) := u;
(%o1)                      f([u]) := u
(%i2) f (1, 2, 3, 4);
(%o2)                     [1, 2, 3, 4]
(%i3) f (a, b, [u]) := [a, b, u];
(%o3)               f(a, b, [u]) := [a, b, u]
(%i4) f (1, 2, 3, 4, 5, 6);
(%o4)                 [1, 2, [3, 4, 5, 6]]

The right hand side of a function is an expression. Thus if you want a sequence of expressions, you do

f(x) := (expr1, expr2, ...., exprn);

and the value of exprn is what is returned by the function.

If you wish to make a return from some expression inside the function then you must use block and return.

block ([], expr1, ..., if (a > 10) then return(a), ..., exprn)

is itself an expression, and so could take the place of the right hand side of a function definition. Here it may happen that the return happens earlier than the last expression.

The first [] in the block, may contain a list of variables and variable assignments, such as [a: 3, b, c: []], which would cause the three variables a,b,and c to not refer to their global values, but rather have these special values for as long as the code executes inside the block, or inside functions called from inside the block. This is called dynamic binding, since the variables last from the start of the block to the time it exits. Once you return from the block, or throw out of it, the old values (if any) of the variables will be restored. It is certainly a good idea to protect your variables in this way. Note that the assignments in the block variables, are done in parallel. This means, that if you had used c: a in the above, the value of c would have been the value of a at the time you just entered the block, but before a was bound. Thus doing something like

block ([a: a], expr1, ... a: a+3, ..., exprn)

will protect the external value of a from being altered, but would let you access what that value was. Thus the right hand side of the assignments, is evaluated in the entering context, before any binding occurs. Using just block ([x], ... would cause the x to have itself as value, just as if it would have if you entered a fresh Maxima session.

The actual arguments to a function are treated in exactly same way as the variables in a block. Thus in

f(x) := (expr1, ..., exprn);



we would have a similar context for evaluation of the expressions as if we had done

block ([x: 1], expr1, ..., exprn)

Inside functions, when the right hand side of a definition, may be computed at runtime, it is useful to use define and possibly buildq.


Function: buildq (variables, expr)

expr is any single Maxima expression and variables is a list of elements of the form <atom> or <atom>: <value>.


The elements of the list variables are evaluated left to right (the syntax atom is equivalent to atom: atom). then these values are substituted into <expression> in parallel. If any atom appears as a single argument to the special form splice (i.e. splice (atom)) inside expr, then the value associated with that atom must be a Maxima list, and it is spliced into expr instead of substituted.


The arguments to buildq need to be protected from simplification until the substitutions have been carried out. This code should effect that by using '.

buildq can be useful for building functions on the fly. One of the powerful things about Maxima is that you can have your functions define other functions to help solve the problem. Further below we discuss building a recursive function, for a series solution. This defining of functions inside functions usually uses define, which evaluates its arguments. A number of examples are included under splice.

Function: splice (atom)
This is used with buildq to construct a list. This is handy for making argument lists, in conjunction with buildq.

mprint ([x]) ::= buildq ([u : x],
  if (debuglevel > 3) print (splice (u)));

Including a call like

mprint ("matrix is", mat, "with length", length(mat))

is equivalent to putting in the line

if (debuglevel > 3) print ("matrix is", mat, "with length", length(mat));

A more non trivial example would try to display the variable values and their names.

mshow (a, b, c) 

should become

print ('a, "=", a, ",", 'b, "=", b, ", and", 'c, "=", c)

so that if it occurs as a line in a program we can print values.

(%i1) foo (x,y,z) := mshow (x, y, z);
(%i2) foo (1, 2, 3);
x = 1 , y = 2 , and z = 3

The actual definition of mshow is the following. Note how buildq lets you build "quoted" structure, so that the 'u lets you get the variable name. Note that in macros, the result is a piece of code which will then be substituted for the macro and evaluated.

mshow ([l]) ::= block ([ans:[], n:length(l)],
    for i:1 thru n do
        (ans: append (ans, buildq ([u: l[i]], ['u, "=", u])),
        if i < n then
            ans: append (ans, if i < n-1 then [","] else [", and"])),
    buildq ([u:ans], print (splice(u))));

The splice also works to put arguments into algebraic operations:

(%i1) buildq ([a: '[b, c, d]], +splice(a));
(%o1)                       d + c + b

Note how the simplification only occurs after the substitution, The operation applying to the splice in the first case is the + while in the second it is the *, yet logically you might think splice(a)+splice(a) could be replaced by 2*splice(a). No simplification takes place with the buildq. To understand what splice is doing with the algebra you must understand that for Maxima, a formula an operation like a+b+c is really internally similar to +(a,b,c), and similarly for multiplication. Thus *(2,b,c,d) is 2*b*c*d.

(%i1) buildq ([a: '[b,c,d]], +splice(a));
(%o1)                       d + c + b
(%i2) buildq ([a: '[b,c,d]], splice(a)+splice(a));
(%o2)                    2 d + 2 c + 2 b


(%i3) buildq ([a: '[b,c,d]], 2*splice(a));
(%o3)                        2 b c d

Finally buildq can be invaluable for building recursive functions. Suppose your program is solving a differential equation using the series method, and has determined that it needs to build a recursion relation

f[n] := -((n^2 - 2*n + 1)*f[n-1] + f[n-2] + f[n-3])/(n^2-n)

and it must do this on the fly inside your function. Now you would really like to add expand.

f[n] := expand (-((n^2 - 2*n + 1)*f[n-1] + f[n-2] + f[n-3])/(n^2-n))

but how do you build this code. You want the expand to happen each time the function runs, not before it.

(%i1) val: -((n^2 - 2*n + 1)*f[n-1] + f[n-2] + f[n-3])/(n^2-n)$
(%i2) define (f[n], buildq ([u: val], expand(u)))$

does the job. This might be useful, since when you do (with expand)

(%i3) f[0]: aa0$
(%i4) f[1]: aa1$
(%i5) f[2]: aa2$
(%i6) f[6];
                       3 aa2   aa1   7 aa0
(%o6)                  ----- + -- + -----
                        10     40     90

where as without it is kept unsimplified, and even after 6 terms it becomes:

(%i7) define (g[n], buildq ([u: val], u))$
(%i8) g[0]: bb0$
(%i9) g[1]: bb1$
(%i10) g[2]: bb2$
(%i11) g[6];
          aa2         7 aa2   aa1   11 aa0    aa1   aa0
          -- - 25 (- ----- - -- - ------) + -- + ---
           4           20     40     120       8    24
(%o11)    ---------------------------------------------
(%i12) expand (%);
                       3 aa2   aa1   7 aa0
(%o12)                 ----- + -- + -----
                        10     40     90

The expression quickly becomes complicated if not simplified at each stage, so the simplification must be part of the definition. Hence the buildq is useful for building the form.

Definitions for Function Definition

Function: apply (f, [x_1, ..., x_n])
Returns the result of applying the function f to the list of arguments x_1, ..., x_n. f is the name of a function or a lambda expression.

This is useful when it is desired to compute the arguments to a function before applying that function. For example, if l is the list [1, 5, -10.2, 4, 3], then apply (min, l) gives -10.2. apply is also useful when calling functions which do not have their arguments evaluated if it is desired to cause evaluation of them. For example, if filespec is a variable bound to the list [test, case] then apply (closefile, filespec) is equivalent to closefile (test, case). In general the first argument to apply should be preceded by a ' to make it evaluate to itself. Since some atomic variables have the same name as certain functions the values of the variable would be used rather than the function because apply has its first argument evaluated as well as its second.

Function: block ([v_1, ..., v_m], expr_1, ..., expr_n)
Function: block (expr_1, ..., expr_n)
block evaluates expr_1, ..., expr_n in sequence and returns the value of the last expression evaluated. The sequence can be modified by the go, throw, and return functions. The last expression is expr_n unless return or an expression containing throw is evaluated. Some variables v_1, ..., v_m can be declared local to the block; these are distinguished from global variables of the same names. If no variables are declared local then the list may be omitted. Within the block, any variable other than v_1, ..., v_m is a global variable.

block saves the current values of the variables v_1, ..., v_m (if any) upon entry to the block, then unbinds the variables so that they evaluate to themselves. The local variables may be bound to arbitrary values within the block but when the block is exited the saved values are restored, and the values assigned within the block are lost.

block may appear within another block. Local variables are established each time a new block is evaluated. Local variables appear to be global to any enclosed blocks. If a variable is non-local in a block, its value is the value most recently assigned by an enclosing block, if any, otherwise, it is the value of the variable in the global environment. This policy may coincide with the usual understanding of "dynamic scope".

If it is desired to save and restore other local properties besides value, for example array (except for complete arrays), function, dependencies, atvalue, matchdeclare, atomgrad, constant, and nonscalar then the function local should be used inside of the block with arguments being the names of the variables.

The value of the block is the value of the last statement or the value of the argument to the function return which may be used to exit explicitly from the block. The function go may be used to transfer control to the statement of the block that is tagged with the argument to go. To tag a statement, precede it by an atomic argument as another statement in the block. For example: block ([x], x:1, loop, x: x+1, ..., go(loop), ...). The argument to go must be the name of a tag appearing within the block. One cannot use go to transfer to a tag in a block other than the one containing the go.

Blocks typically appear on the right side of a function definition but can be used in other places as well.

Function: break (expr_1, ..., expr_n)
Evaluates and prints expr_1, ..., expr_n and then causes a Maxima break at which point the user can examine and change his environment. Upon typing exit; the computation resumes.

Function: catch (expr_1, ..., expr_n)
Evaluates expr_1, ..., expr_n one by one; if any leads to the evaluation of an expression of the form throw (arg), then the value of the catch is the value of throw (arg), and no further expressions are evaluated. This "non-local return" thus goes through any depth of nesting to the nearest enclosing catch. If there is no catch enclosing a throw, an error message is printed.

If the evaluation of the arguments does not lead to the evaluation of any throw then the value of catch is the value of expr_n.

(%i1) lambda ([x], if x < 0 then throw(x) else f(x))$
(%i2) g(l) := catch (map ("%, l))$
(%i3) g ([1, 2, 3, 7]);
(%o3)               [f(1), f(2), f(3), f(7)]
(%i4) g ([1, 2, -3, 7]);
(%o4)                          - 3

The function g returns a list of f of each element of l if l consists only of non-negative numbers; otherwise, g "catches" the first negative element of l and "throws" it up.

Function: compfile (filename, f_1, ..., f_n)
Translates Maxima functions f_1, ..., f_n into Lisp and writes the translated code into the file filename.

The Lisp translations are not evaluated, nor is the output file processed by the Lisp compiler. translate creates and evaluates Lisp translations. compile_file translates Maxima into Lisp, and then executes the Lisp compiler.

See also translate, translate_file, and compile_file.

Function: compile (f_1, ..., f_n)
Function: compile (functions)
Function: compile (all)
Translates Maxima functions f_1, ..., f_n into Lisp, evaluates the Lisp translations, and calls the Lisp function COMPILE on each translated function. compile returns a list of the names of the compiled functions.

compile (all) or compile (functions) compiles all user-defined functions.

compile quotes its arguments; the double-single-quotes operator '' defeats quotation.

Function: define (f(x_1, ..., x_n), expr)
Defines a function named f with arguments x_1, ..., x_n and function body expr.

define quotes its first argument in most cases, and evaluates its second argument unless explicitly quoted. However, if the first argument is an expression of the form ev (expr), funmake (expr), or arraymake (expr), the first argument is evaluated; this allows for the function name to be computed, as well as the body.

define is similar to the function definition operator :=, but when define appears inside a function, the definition is created using the value of expr at execution time rather than at the time of definition of the function which contains it.

All function definitions appear in the same namespace; defining a function f within another function g does not limit the scope of f to g.


(%i1) foo: 2^bar;
(%o1)                         2
(%i2) g(x) := (f_1 (y) :=   foo*x*y,
               f_2 (y) := "foo*x*y,
       define (f_3 (y),     foo*x*y),
       define (f_4 (y),   "foo*x*y));
(%o2) g(x) := (f_1(y) := foo x y, f_2(y) := 2    x y, 
               define(f_3(y), foo x y), define(f_4(y), 2    x y))
(%i3) functions;
(%o3)                        [g(x)]
(%i4) g(a);
(%o4)                  f_4(y) := a 2    y
(%i5) functions;
(%o5)        [g(x), f_1(y), f_2(y), f_3(y), f_4(y)]
(%i6) dispfun (f_1, f_2, f_3, f_4);
(%t6)                   f_1(y) := foo x y

(%t7)                  f_2(y) := 2    x y

(%t8)                  f_3(y) := a 2    y

(%t9)                  f_4(y) := a 2    y

(%o9)                         done

Function: define_variable (name, default_value, mode)

Introduces a global variable into the Maxima environment. define_variable is useful in user-written packages, which are often translated or compiled.

define_variable carries out the following steps:

  1. mode_declare (name, mode) declares the mode of name to the translator. See mode_declare for a list of the possible modes.
  2. If the variable is unbound, default_value is assigned to name.
  3. declare (name, special) declares it special.
  4. Associates name with a test function to ensure that name is only assigned values of the declared mode.

The value_check property can be assigned to any variable which has been defined via define_variable with a mode other than any. The value_check property is a lambda expression or the name of a function of one variable, which is called when an attempt is made to assign a value to the variable. The argument of the value_check function is the would-be assigned value.

define_variable evaluates default_value, and quotes name and mode. define_variable returns the current value of name, which is default_value if name was unbound before, and otherwise it is the previous value of name.


foo is a Boolean variable, with the initial value true.

(%i1) define_variable (foo, true, boolean);
(%o1)                         true
(%i2) foo;
(%o2)                         true
(%i3) foo: false;
(%o3)                         false
(%i4) foo: %pi;
Error: foo was declared mode boolean, has value: %pi
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i5) foo;
(%o5)                         false

bar is an integer variable, which must be prime.

(%i1) define_variable (bar, 2, integer);
(%o1)                           2
(%i2) qput (bar, prime_test, value_check);
(%o2)                      prime_test
(%i3) prime_test (y) := if not primep(y) then error (y, "is not prime.");
(%o3) prime_test(y) := if not primep(y)

                                   then error(y, "is not prime.")
(%i4) bar: 1439;
(%o4)                         1439
(%i5) bar: 1440;
1440 is not prime.
#0: prime_test(y=1440)
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i6) bar;
(%o6)                         1439

baz_quux is a variable which cannot be assigned a value. The mode any_check is like any, but any_check enables the value_check mechanism, and any does not.

(%i1) define_variable (baz_quux, 'baz_quux, any_check);
(%o1)                       baz_quux
(%i2) F: lambda ([y], if y # 'baz_quux then error ("Cannot assign to `baz_quux'."));
(%o2) lambda([y], if y # 'baz_quux

                        then error(Cannot assign to `baz_quux'.))
(%i3) qput (baz_quux, "F, value_check);
(%o3) lambda([y], if y # 'baz_quux

                        then error(Cannot assign to `baz_quux'.))
(%i4) baz_quux: 'baz_quux;
(%o4)                       baz_quux
(%i5) baz_quux: sqrt(2);
Cannot assign to `baz_quux'.
#0: lambda([y],if y # 'baz_quux then error("Cannot assign to `baz_quux'."))(y=sqrt(2))
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i6) baz_quux;
(%o6)                       baz_quux

Function: dispfun (f_1, ..., f_n)
Function: dispfun (all)
Displays the definition of the user-defined functions f_1, ..., f_n. Each argument may be the name of a macro (defined with ::=), an ordinary function (defined with := or define), an array function (defined with := or define, but enclosing arguments in square brackets [ ]), a subscripted function, (defined with := or define, but enclosing some arguments in square brackets and others in parentheses ( )) one of a family of subscripted functions selected by a particular subscript value, or a subscripted function defined with a constant subscript.

dispfun (all) displays all user-defined functions as given by the functions, arrays, and macros lists, omitting subscripted functions defined with constant subscripts.

dispfun creates an intermediate expression label (%t1, %t2, etc.) for each displayed function, and assigns the function definition to the label. In contrast, fundef returns the function definition.

dispfun quotes its arguments; the double-single-quote operator '' defeats quotation. dispfun always returns done.


(%i1) m(x, y) ::= x^(-y)$
(%i2) f(x, y) :=  x^(-y)$
(%i3) g[x, y] :=  x^(-y)$
(%i4) h[x](y) :=  x^(-y)$
(%i5) i[8](y) :=  8^(-y)$
(%i6) dispfun (m, f, g, h, h[5], h[10], i[8])$
                                     - y
(%t6)                   m(x, y) ::= x

                                     - y
(%t7)                    f(x, y) := x

                                    - y
(%t8)                     g     := x
                           x, y

                                    - y
(%t9)                     h (y) := x

(%t10)                     h (y) := --
                            5        y

(%t11)                    h  (y) := ---
                           10         y

                                    - y
(%t12)                    i (y) := 8

System variable: functions
Default value: []

functions is the list of user-defined Maxima functions in the current session. A user-defined function is a function constructed by define or :=. A function may be defined at the Maxima prompt or in a Maxima file loaded by load or batch. Lisp functions, however, are not added to functions.

Function: fundef (f)
Returns the definition of the function f.

The argument may be the name of a macro (defined with ::=), an ordinary function (defined with := or define), an array function (defined with := or define, but enclosing arguments in square brackets [ ]), a subscripted function, (defined with := or define, but enclosing some arguments in square brackets and others in parentheses ( )) one of a family of subscripted functions selected by a particular subscript value, or a subscripted function defined with a constant subscript.

fundef quotes its argument; the double-single-quote operator '' defeats quotation.

fundef (f) returns the definition of f. In contrast, dispfun (f) creates an intermediate expression label and assigns the definition to the label.

Function: funmake (name, [arg_1, ..., arg_n])
Returns an expression name (arg_1, ..., arg_n). The return value is simplified, but not evaluated, so the function is not called.

funmake evaluates its arguments.


Function: lambda ([x_1, ..., x_m], expr_1, ..., expr_n)
Defines and returns a lambda expression (that is, an anonymous function) with arguments x_1, ..., x_m and return value expr_n. A lambda expression can be assigned to a variable and evaluated like an ordinary function. A lambda expression may appear in contexts in which a function evaluation (but not a function name) is expected.

When the function is evaluated, unbound local variables x_1, ..., x_m are created. lambda may appear within block or another lambda; local variables are established each time another block or lambda is evaluated. Local variables appear to be global to any enclosed block or lambda. If a variable is not local, its value is the value most recently assigned in an enclosing block or lambda, if any, otherwise, it is the value of the variable in the global environment. This policy may coincide with the usual understanding of "dynamic scope".

After local variables are established, expr_1 through expr_n are evaluated in turn. The special variable %%, representing the value of the preceding expression, is recognized. throw and catch may also appear in the list of expressions.

return cannot appear in a lambda expression unless enclosed by block, in which case return defines the return value of the block and not of the lambda expression, unless the block happens to be expr_n. Likewise, go cannot appear in a lambda expression unless enclosed by block.

lambda quotes its arguments; the double-single-quote operator '' defeats quotation.


(%i1) f: lambda ([x], x^2);
(%o1)                    lambda([x], x )
(%i2) f(a);
(%o2)                          a
(%i3) lambda ([x], x^2) (a);
(%o3)                          a
(%i4) apply (lambda ([x], x^2), [a]);
(%o4)                          a
(%i5) map (lambda ([x], x^2), [a, b, c, d, e]);
                        2   2   2   2   2
(%o5)                 [a , b , c , d , e ]
(%i6) a: %pi$
(%i7) b: %e$
(%i8) g: lambda ([a], a*b);
(%o8)                   lambda([a], a b)
(%i9) b: %gamma$
(%i10) g(1/2);
(%o10)                       ------
(%i11) g2: lambda ([a], a*"b);
(%o11)                lambda([a], a %gamma)
(%i12) b: %e$
(%i13) g2(1/2);
(%o13)                       ------
(%i14) h: lambda ([a, b], h2: lambda ([a], a*b), h2(1/2));
(%o14)    lambda([a, b], h2 : lambda([a], a b), h2(-))
(%i15) h(%pi, %gamma);
(%o15)                       ------
(%i16) i: lambda ([a], lambda ([x], a*x));
(%o16)            lambda([a], lambda([x], a x))
(%i17) i(1/2);
(%o17)                  lambda([x], a x)
(%i18) i2: lambda([a], buildq([a: a], lambda([x], a*x)));
(%o18)    lambda([a], buildq([a : a], lambda([x], a x)))
(%i19) i2(1/2);
(%o19)                   lambda([x], -)
(%i20) i2(1/2)(%pi);
(%o20)                         ---

Function: local (v_1, ..., v_n)
Declares the variables v_1, ..., v_n to be local with respect to all the properties in the statement in which this function is used.

local quotes its arguments. local returns done.

local may only be used in block, in the body of function definitions or lambda expressions, or in the ev function, and only one occurrence is permitted in each.

local is independent of context.

Option variable: macroexpansion
Default value: false

macroexpansion controls advanced features which affect the efficiency of macros. Possible settings:

Option variable: mode_checkp
Default value: true

When mode_checkp is true, mode_declare checks the modes of bound variables.

Option variable: mode_check_errorp
Default value: false

When mode_check_errorp is true, mode_declare calls error.

Option variable: mode_check_warnp
Default value: true

When mode_check_warnp is true, mode errors are described.

Function: mode_declare (y_1, mode_1, ..., y_n, mode_n)
mode_declare is used to declare the modes of variables and functions for subsequent translation or compilation of functions. mode_declare is typically placed at the beginning of a function definition, at the beginning of a Maxima script, or executed at the interactive prompt.

The arguments of mode_declare are pairs consisting of a variable and a mode which is one of boolean, fixnum, number, rational, or float. Each variable may also be a list of variables all of which are declared to have the same mode.

If a variable is an array, and if every element of the array which is referenced has a value then array (yi, complete, dim1, dim2, ...) rather than

array(yi, dim1, dim2, ...)

should be used when first declaring the bounds of the array. If all the elements of the array are of mode fixnum (float), use fixnum (float) instead of complete. Also if every element of the array is of the same mode, say m, then

mode_declare (completearray (yi), m))

should be used for efficient translation.

Numeric code using arrays might run faster by declaring the expected size of the array, as in:

mode_declare (completearray (a [10, 10]), float)

for a floating point number array which is 10 x 10.

One may declare the mode of the result of a function by using function (f_1, f_2, ...) as an argument; here f_1, f_2, ... are the names of functions. For example the expression,

mode_declare ([function (f_1, f_2, ...)], fixnum)

declares that the values returned by f_1, f_2, ... are single-word integers.

modedeclare is a synonym for mode_declare.

Function: mode_identity (arg_1, arg_2)
A special form used with mode_declare and macros to declare, e.g., a list of lists of flonums, or other compound data object. The first argument to mode_identity is a primitive value mode name as given to mode_declare (i.e., one of float, fixnum, number, list, or any), and the second argument is an expression which is evaluated and returned as the value of mode_identity. However, if the return value is not allowed by the mode declared in the first argument, an error or warning is signalled. The important thing is that the mode of the expression as determined by the Maxima to Lisp translator, will be that given as the first argument, independent of anything that goes on in the second argument. E.g., x: 3.3; mode_identity (fixnum, x); yields an error. mode_identity (flonum, x) returns 3.3 . This has a number of uses, e.g., if you knew that first (l) returned a number then you might write mode_identity (number, first (l)). However, a more efficient way to do it would be to define a new primitive,

firstnumb (x) ::= buildq ([x], mode_identity (number, x));

and use firstnumb every time you take the first of a list of numbers.

Option variable: transcompile
Default value: true

When transcompile is true, translate and translate_file generate declarations to make the translated code more suitable for compilation.

compfile sets transcompile: true for the duration.

Function: translate (f_1, ..., f_n)
Function: translate (functions)
Function: translate (all)
Translates the user-defined functions f_1, ..., f_n from the Maxima language into Lisp and evaluates the Lisp translations. Typically the translated functions run faster than the originals.

translate (all) or translate (functions) translates all user-defined functions.

Functions to be translated should include a call to mode_declare at the beginning when possible in order to produce more efficient code. For example:

f (x_1, x_2, ...) := block ([v_1, v_2, ...],
    mode_declare (v_1, mode_1, v_2, mode_2, ...), ...)

where the x_1, x_2, ... are the parameters to the function and the v_1, v_2, ... are the local variables.

The names of translated functions are removed from the functions list if savedef is false (see below) and are added to the props lists.

Functions should not be translated unless they are fully debugged.

Expressions are assumed simplified; if they are not, correct but non- optimal code gets generated. Thus, the user should not set the simp switch to false which inhibits simplification of the expressions to be translated.

The switch translate, if true, causes automatic translation of a user's function to Lisp.

Note that translated functions may not run identically to the way they did before translation as certain incompatabilities may exist between the Lisp and Maxima versions. Principally, the rat function with more than one argument and the ratvars function should not be used if any variables are mode_declare'd canonical rational expressions (CRE). Also the prederror: false setting will not translate.

savedef - if true will cause the Maxima version of a user function to remain when the function is translate'd. This permits the definition to be displayed by dispfun and allows the function to be edited.

transrun - if false will cause the interpreted version of all functions to be run (provided they are still around) rather than the translated version.

The result returned by translate is a list of the names of the functions translated.

Function: translate_file (maxima_filename)
Function: translate_file (maxima_filename, lisp_filename)
Translates a file of Maxima code into a file of Lisp code. translate_file returns a list of three filenames: the name of the Maxima file, the name of the Lisp file, and the name of file containing additional information about the translation. translate_file evaluates its arguments.

translate_file ("foo.mac"); load("foo.LISP") is the same as batch ("foo.mac") except for certain restrictions, the use of '' and %, for example.

translate_file (maxima_filename) translates a Maxima file maxima_filename into a similarly-named Lisp file. For example, foo.mac is translated into foo.LISP. The Maxima filename may include a directory name or names, in which case the Lisp output file is written to the same directory from which the Maxima input comes.

translate_file (maxima_filename, lisp_filename) translates a Maxima file maxima_filename into a Lisp file lisp_filename. translate_file ignores the filename extension, if any, of lisp_filename; the filename extension of the Lisp output file is always LISP. The Lisp filename may include a directory name or names, in which case the Lisp output file is written to the specified directory.

translate_file also writes a file of translator warning messages of various degrees of severity. The filename extension of this file is UNLISP. This file may contain valuable information, though possibly obscure, for tracking down bugs in translated code. The UNLISP file is always written to the same directory from which the Maxima input comes.

translate_file emits Lisp code which causes some declarations and definitions to take effect as soon as the Lisp code is compiled. See compile_file for more on this topic.

See also tr_array_as_ref, tr_bound_function_applyp, tr_exponent, tr_file_tty_messagesp, tr_float_can_branch_complex, tr_function_call_default, tr_numer, tr_optimize_max_loop, tr_semicompile, tr_state_vars, tr_warnings_get, tr_warn_bad_function_calls, tr_warn_fexpr, tr_warn_meval, tr_warn_mode, tr_warn_undeclared, tr_warn_undefined_variable, and tr_windy.

Option variable: transrun
Default value: true

When transrun is false will cause the interpreted version of all functions to be run (provided they are still around) rather than the translated version.

Option variable: tr_array_as_ref
Default value: true

If translate_fast_arrays is false, array references in Lisp code emitted by translate_file are affected by tr_array_as_ref. When tr_array_as_ref is true, array names are evaluated, otherwise array names appear as literal symbols in translated code.

tr_array_as_ref has no effect if translate_fast_arrays is true.

Option variable: tr_bound_function_applyp
Default value: true

When tr_bound_function_applyp is true, Maxima gives a warning if a bound variable (such as a function argument) is found being used as a function. tr_bound_function_applyp does not affect the code generated in such cases.

For example, an expression such as g (f, x) := f (x+1) will trigger the warning message.

Option variable: tr_file_tty_messagesp
Default value: false

When tr_file_tty_messagesp is true, messages generated by translate_file during translation of a file are displayed on the console and inserted into the UNLISP file. When false, messages about translation of the file are only inserted into the UNLISP file.

Option variable: tr_float_can_branch_complex
Default value: true

Tells the Maxima-to-Lisp translator to assume that the functions acos, asin, asec, and acsc can return complex results.

The ostensible effect of tr_float_can_branch_complex is the following. However, it appears that this flag has no effect on the translator output.

When it is true then acos(x) is of mode any even if x is of mode float (as set by mode_declare). When false then acos(x) is of mode float if and only if x is of mode float.

Option variable: tr_function_call_default
Default value: general

false means give up and call meval, expr means assume Lisp fixed arg function. general, the default gives code good for mexprs and mlexprs but not macros. general assures variable bindings are correct in compiled code. In general mode, when translating F(X), if F is a bound variable, then it assumes that apply (f, [x]) is meant, and translates a such, with apropriate warning. There is no need to turn this off. With the default settings, no warning messages implies full compatibility of translated and compiled code with the Maxima interpreter.

Option variable: tr_numer
Default value: false

When tr_numer is true numer properties are used for atoms which have them, e.g. %pi.

Option variable: tr_optimize_max_loop
Default value: 100

tr_optimize_max_loop is the maximum number of times the macro-expansion and optimization pass of the translator will loop in considering a form. This is to catch macro expansion errors, and non-terminating optimization properties.

Option variable: tr_semicompile
Default value: false

When tr_semicompile is true, translate_file and compfile output forms which will be macroexpanded but not compiled into machine code by the Lisp compiler.

System variable: tr_state_vars
Default value:
[transcompile, tr_semicompile, tr_warn_undeclared, tr_warn_meval,
tr_warn_fexpr, tr_warn_mode, tr_warn_undefined_variable,
tr_function_call_default, tr_array_as_ref,tr_numer]

The list of the switches that affect the form of the translated output. This information is useful to system people when trying to debug the translator. By comparing the translated product to what should have been produced for a given state, it is possible to track down bugs.

Function: tr_warnings_get ()
Prints a list of warnings which have been given by the translator during the current translation.

Option variable: tr_warn_bad_function_calls
Default value: true

- Gives a warning when when function calls are being made which may not be correct due to improper declarations that were made at translate time.

Option variable: tr_warn_fexpr
Default value: compfile

- Gives a warning if any FEXPRs are encountered. FEXPRs should not normally be output in translated code, all legitimate special program forms are translated.

Option variable: tr_warn_meval
Default value: compfile

- Gives a warning if the function meval gets called. If meval is called that indicates problems in the translation.

Option variable: tr_warn_mode
Default value: all

- Gives a warning when variables are assigned values inappropriate for their mode.

Option variable: tr_warn_undeclared
Default value: compile

- Determines when to send warnings about undeclared variables to the TTY.

Option variable: tr_warn_undefined_variable
Default value: all

- Gives a warning when undefined global variables are seen.

Option variable: tr_windy
Default value: true

- Generate "helpfull" comments and programming hints.

Function: compile_file (filename)
Function: compile_file (filename, compiled_filename)
Function: compile_file (filename, compiled_filename, lisp_filename)
Translates the Maxima file filename into Lisp, executes the Lisp compiler, and, if the translation and compilation succeed, loads the compiled code into Maxima.

compile_file returns a list of the names of four files: the original Maxima file, the Lisp translation, notes on translation, and the compiled code. If the compilation fails, the fourth item is false.

Some declarations and definitions take effect as soon as the Lisp code is compiled (without loading the compiled code). These include functions defined with the := operator, macros define with the ::= operator, alias, declare, define_variable, mode_declare, and infix, matchfix, nofix, postfix, prefix, and compfile.

Assignments and function calls are not evaluated until the compiled code is loaded. In particular, within the Maxima file, assignments to the translation flags (tr_numer, etc.) have no effect on the translation.

filename may not contain :lisp statements.

compile_file evaluates its arguments.

Function: declare_translated (f_1, f_2, ...)
When translating a file of Maxima code to Lisp, it is important for the translator to know which functions it sees in the file are to be called as translated or compiled functions, and which ones are just Maxima functions or undefined. Putting this declaration at the top of the file, lets it know that although a symbol does which does not yet have a Lisp function value, will have one at call time. (MFUNCTION-CALL fn arg1 arg2 ...) is generated when the translator does not know fn is going to be a Lisp function.

Go to the first, previous, next, last section, table of contents.