19.11.2014 Views

The Fortress Language Specification - CiteSeerX

The Fortress Language Specification - CiteSeerX

The Fortress Language Specification - 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.

printFirst(xs : R . . .) =<br />

if |xs| > 0 then print xs 0<br />

else throw Error end<br />

This function takes an arbitrary number of floats and prints the first one (unless it is given zero arguments; then it<br />

throws an exception).<br />

2.6.3 Function Overloading<br />

Functions can be overloaded in <strong>Fortress</strong> by the types of their parameters. Calls to overloaded functions are resolved<br />

based on the runtime types of the arguments. For example, the following function is overloaded based on parameter<br />

type:<br />

size(x :Tree) = 1 + size(leftBranch(x)) + size(rightBranch(x))<br />

size(x :List) = 1 + size(rest(x))<br />

Suppose we call size on an object with runtime type List, the second definition of size will be invoked regardless of<br />

the static type of the argument. Of course, function applications are statically checked to ensure that some definition<br />

will be applicable at run time, and that the definition to apply will be unambiguous.<br />

2.6.4 Function Contracts<br />

<strong>Fortress</strong> allows contracts to be included in function declarations. Among other things, contracts allow us to require<br />

that the argument to a function satisfies a given set of constraints, and to ensure that the resulting value satisfies<br />

some constraints. <strong>The</strong>y provide essential documentation for the clients of a function, enabling us to express semantic<br />

properties that cannot be expressed through the static type system.<br />

Contracts are placed at the end of a function header, before the function body. For example, we can place a contract<br />

on our factorial function requiring that its argument be nonnegative as follows:<br />

factorial(n) requires n ≥ 0<br />

= if n = 0 then 1<br />

else n factorial(n − 1) end<br />

We can also ensure that the result of factorial is itself nonnegative:<br />

factorial(n)<br />

requires n ≥ 0<br />

ensures result ≥ 0<br />

= if n = 0 then 1<br />

else n factorial(n − 1) end<br />

<strong>The</strong> variable result is bound in the ensures clause to the return value of the function.<br />

2.7 Some Common Expressions in <strong>Fortress</strong><br />

We have already seen an if expression in <strong>Fortress</strong>. Here’s an example of a while expression:<br />

24

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

Saved successfully!

Ooh no, something went wrong!