A simple Hope example - conditionals

Let's see how we can define max in Hope. Like Pascal, it's a strongly-typed language, which means we must tell the compiler about the types of all objects in our programs so it can check that they're used consistently. The function definition comes in two parts. First we declare the argument and result types:

     dec max : num # num -> num ;
dec is a reserved word: you can't use it as a name. max is the name of the function being defined. Names consist of upper and lower case letters (which are distinct) and digits, and must start with a letter. The current fashion is to use lower case. The layout isn't significant and you can separate symbols with any number of blanks, tabs and newlines for clarity, as in this example. Symbols need only be separated when they might otherwise be confused as one, such as dec and max.

The next part of the declaration gives the types of the arguments (read the symbol : as `takes a'). Non-negative integers are of the predefined type num (in lower case). # is read as `and a'; (or you can use the reserved word X). -> is read as `yields'. The semicolon marks the end of the declaration, which tells the compiler that max takes two numbers as arguments and returns a single number as its result.

The result of a function is defined by one or more recursion equations. max needs only one equation to define it:

     --- max ( x, y ) <=  if x > y then x else y ;
Read the symbol -- as `the value of'. The expression max ( x, y ) is called the left-hand side of the equation. It defines x and y as formal parameters, or local names for the values that will be supplied when the function is applied. Parameter names are local to the equation, so x and y won't be confused with any other x or y in the program. The symbol <= is read as `is defined as'.

The rest of the equation (called the right-hand side) defines the result. It's a conditional expression. The symbols if, then and else are reserved words. Pascal's conditional statement chooses between alternative actions, but Hope's conditional expression chooses between alternative values, in line with our view that function applications are ways of writing values rather than recipes for computing them. If the value of the expression x > y is true, the value of the whole conditional expression is the value of x, otherwise it's the value of y. The alternative values can be defined by any Hope expressions.

When the value of a function is defined by more than one expression like this, they are evaluated in an unspecified order. On a suitable computer, such as the Imperial College ALICE machine, it's even possible to evaluate both expressions and the test in parallel and throw away one of the values according to the result of the test.



Roger Bailey <rb@doc.ic.ac.uk>