[top] [prev] [next]

Example module and interface

Here is the canonical example of a public stack with hidden representation:

    INTERFACE Stack;
      TYPE T <: REFANY;
      PROCEDURE Create(): T;
      PROCEDURE Push(VAR s: T; x: REAL);
      PROCEDURE Pop(VAR s: T): REAL;
    END Stack.

    MODULE Stack;
      REVEAL T = BRANDED OBJECT item: REAL; link: T END;
      PROCEDURE Create(): T = BEGIN RETURN NIL END Create;

      PROCEDURE Push(VAR s: T; x: REAL) =
          s := NEW(T, item := x, link := s)
        END Push;

      PROCEDURE Pop(VAR s: T): REAL =
        VAR res: REAL;
          res := s.item; s := s.link; RETURN res
        END Pop;

    END Stack.

If the representation of stacks is required in more than one module, it should be moved to a private interface, so that it can be imported wherever it is required:

    INTERFACE Stack  (* ... as before ... *) END Stack.

    INTERFACE StackRep; IMPORT Stack;   
      REVEAL Stack.T = BRANDED OBJECT item: REAL; link: Stack.T END
    END StackRep.

    MODULE Stack; IMPORT StackRep;
      (* Push, Pop, and Create as before *)
    END Stack.

[top] [prev] [next]