4.3 Functions

Many standard mathematical and operating system functions are pre-defined within Pyxplot’s mathematical environment. These range from everyday examples like trigonometric functions, to very specialised functions; there is even a function to return the phase of the Moon on any given day. As with the mathematical constant, common functions are defined in the user’s default namespace, for example

pyxplot> print exp(2)

whilst others live in modules, for example

print ast.moonPhase( time.now() )

which returns the present phase of the Moon in radians, and

print os.path.filesize("/etc/passwd")

which returns the size of a file (in units of bytes, of course!).

A complete list of these functioned, sorted by module, can be found in Chapter 12. Another quick way to find out some more information about a function is the print the function object, for example:

pyxplot> print log
log(x) returns the natural logarithm of x.

All, of Pyxplot’s built-in constants, functions and modules are contained in the module defaults, which can also be printed to view its contents:

print defaults

It is possible to access pi, for example, as defaults.pi, though in practice this syntax is very rarely needed. All of the objects in the defaults module are always accessible by name (i.e. they are always in any namespace), unless another local or global variable exists with the same name.

The user can define his own algebraic function definitions using a similar syntax to that used to declare new variables, as in the examples:

f()    = pi
g(x)   = x*sin(x)
h(x,y) = x*y

Function objects are just like any other variables, and can even be used as arguments to other functions:

pyxplot> f = sum
pyxplot> print f
sum(...) returns the sum of its arguments.
pyxplot> f = sin
pyxplot> g(x,y) = x(x(y))
pyxplot> print g(f,1)

User-defined functions can be undefined in the same way as any other variable, for example by typing:

f =

Where the logic required to define a particular function is greater than can be contained in a single algebraic expression, a subroutine should be used (see Section 7.8); these allow an arbitrary numbers of lines of Pyxplot code to be executed whenever a function is evaluated.