Perfect Developer basic tutorial 4 This page last modified 2011-10-30 (JAC)

More functions

Let's provide some sort of access to the authors attribute of our Book objects.

Rather than make authors publicly readable, instead we will add a method to check whether a particular person is included in authors. We can do this by adding a method hasAuthor as follows:

class Book ^=
abstract
  var title: string,
      authors: set of string;
interface
  function
title;

  function hasAuthor(author: string): bool
    ^= author in authors;

  build{!title: string, !authors: set of string};
 
  build{!title: string, author: string}
    post authors! = set of string{author};
end;

Now we can use the expression b.hasAuthor("Douglas Adams") to check whether "Douglas Adams" is one of the authors of the Book object b.

Looking at the function declaration in more detail, we can see that it comprises the keyword function followed by the name we have chosen, then comes the parameter list (if there are any parameters), then the return type is declared (after a colon, just as for variables and parameters).

switched-on lamp Note that a function is not allowed to change either the abstract data of the object it is called on, nor its parameters - all it can do is return a value. (Actually, functions can return several values at once, but we'll skip this facility for now).

Let's add a second way of accessing the authors variable, by declaring a function to return any one of the authors. Of course, when there are several such authors, the result is not precisely defined. The function is therefore nondeterministic, which we indicate by declaring it opaque. Here is one way of declaring an anyAuthor function:

class Book ^=
abstract
  var title: string,
      authors: set of string;
interface
  function
title;

  function hasAuthor(author: string): bool
    ^= author in authors;

  opaque function anyAuthor: string
    ^= any authors;


  build{!title: string, !authors: set of string};
 
  build{!title: string, author: string}
    post authors! = set of string{author};
end;

We have defined anyAuthor using an any expression to choose any element from the collection authors.

However, there is another way we can specify what a function returns, which is particularly useful for opaque functions:

opaque function anyAuthor: string
  satisfy result in authors;

Instead of using the is-defined-as symbol ^= to define the return value, we use the keyword satisfy to introduce a condition (or several comma-separated conditions) that the result must obey.

Before we move on, take a good look at the Book class we have arrived at. Can you see any problems with it in general, and with the anyAuthor function (expressed in either way) in particular?

Next:  Try it out!

 

Save My Place Glossary Language Reference Manual
Tutorials Overview Main site   
Copyright © 1997-2012 Escher Technologies Limited. All rights reserved. Information is subject to change without notice.