Modula-2 Reloaded

A Modern Typesafe & Literate Programming Notation

Site Menu

Project

Specification

Implementation

Recommendations

Reference

Needs Updating

Work in Progress

Wastebasket

Wiki Manual

edit SideBar

Operator Binding Example For Approach 2 Z-Type

DEFINITION MODULE INT;

(* Example library for a signed integer type using operator bindings *) 


FROM FileIO IMPORT File; (* required for IO *)


(* INT type *)

TYPE
    SampleINT = OPAQUE RECORD ("Z-Type")
        value : ARRAY 2 OF OCTET; (* 16 bits *)
    END; 


(* range *) 

CONST [TMIN] minValue = -32768; 

CONST [TMAX] maxValue = 32767;


(* assignment *)

PROCEDURE [:=] assign ( VAR assignTo : INT; literal : ARRAY OF CHAR ); 


(* type conversions *)

PROCEDURE [::] toCARD  ( n : INT ) : CARDINAL; 

PROCEDURE [::] toINT ( n : INT ) : INTEGER; 

PROCEDURE [::] toREAL ( n : INT ) : REAL;


(* experimental *)

PROCEDURE [::] fromCARD  ( n : CARDINAL ) : INT; 

PROCEDURE [::] fromINT  ( n : INTEGER ) : INT;


(* monadic arithmetic operations *) 

PROCEDURE [ABS] abs ( n : INT ) : INT; 

PROCEDURE [NEG] neg ( n : INT ) : INT; 

PROCEDURE [ODD] odd ( n : INT ) : BOOLEAN; 


(* dyadic arithmetic operations *) 

PROCEDURE [+] add ( n, m : INT ) : INT; 

PROCEDURE [-] sub ( n, m : INT ) : INT; 

PROCEDURE [*] multiply ( n, m : INT ) : INT; 

PROCEDURE [DIV] divide ( n, m : INT ) : INT; 

PROCEDURE [MOD] modulo ( n, m : INT ) : INT; 


(* relational operations *) 

PROCEDURE [=] isEqual ( n, m : INT ) : BOOLEAN; 

PROCEDURE [<] isLess ( n, m : INT ) : BOOLEAN; 

PROCEDURE [>] isGreater ( n, m : INT ) : BOOLEAN; 


(* scalar conversion primitives *)

CONST digitCapacity = 4; (* total digits in native radix *)

PROCEDURE [TO] toSXF ( n : INT; VAR s : ARRAY OF CHAR );
(* convert an INT value to a string in scalar exchange format *)

PROCEDURE [FROM] fromSXF ( VAR n : INT; s : ARRAY OF CHAR );
(* convert a string in scalar exchange format to an INT value *)


(* IO operations, bound to READ, WRITE and WRITEF *)

PROCEDURE Read( infile : File; VAR b : INT );
(* Reads the textual representation of an INT value in simple format from input stream infile
   - any leading whitespace is skipped
   - any remaining characters that are part of the numeral being read are removed from infile
   - the numeric value of the numeral string read is assigned to the variable passed in for b
   - the file status is set to any of success, outOfRange, wrongFormat, endOfLine, or endOfInput *)

PROCEDURE Write( outfile : File; b : SampleINT );
(* Writes the textual representation of value b in simple format to output stream outfile *)

PROCEDURE WriteF( outfile : File; fmtStr : ARRAY OF CHAR;
                  items : CARDINAL; VARIADIC v[items] OF b : INT );
(* Writes a formatted textual representation of one or more INT values to output stream outfile. The
   value of parameter items is calculated and inserted automatically. The output format is determined by fmtStr. *)

END INT.