03.08.2013 Views

PTOLEMY II - CiteSeerX

PTOLEMY II - CiteSeerX

PTOLEMY II - CiteSeerX

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Expressions<br />

MATLAB-style syntax. For example, to obtain an array with the integers from 1 to 100, you can enter:<br />

[1:1:100].toArray()<br />

3.6 Defining Functions<br />

The expression language supports definition of functions. The syntax is:<br />

function(arg1:Type, arg2:Type...)<br />

function body<br />

where “function” is the keyword for defining a function. The type of an argument can be left unspecified,<br />

in which case the expression language will attempt to infer it. The function body gives an expression<br />

that defines the return value of the function. The return type is always inferred based on the<br />

argument type and the expression. For example:<br />

function(x:double) x*5.0<br />

defines a function that takes a double argument, multiplies it by 5.0, and returns a double. The return<br />

value of the above expression is the function itself. Thus, for example, the expression evaluator yields:<br />

>> function(x:double) x*5.0<br />

(function(x:double) (x*5.0))<br />

>><br />

To apply the function to an argument, simply do<br />

>> (function(x:double) x*5.0) (10.0)<br />

50.0<br />

>><br />

Alternatively, in the expression evaluator, you can assign the function to a variable, and then use the<br />

variable name to apply the function. For example,<br />

>> f = function(x:double) x*5.0<br />

(function(x:double) (x*5.0))<br />

>> f(10)<br />

50.0<br />

>><br />

Functions can be passed as arguments to certain “higher-order functions” that have been defined<br />

(see table Table 9 on page 125). For example, the iterate() function takes three arguments, a function,<br />

an integer, and an initial value to which to apply the function. It applies the function first to the initial<br />

value, then to the result of the application, then to that result, collecting the results into an array whose<br />

108 Ptolemy <strong>II</strong>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!