The Northern Spy: Modula-2 R10 Templates
TweetFollow Us on Twitter

The Northern Spy: Modula-2 R10 Templates

By Rick Sutcliffe

Modula-2 R10 has been the Spy's meat and potatoes in this space for a few months now. It is the fully modern dialect of Niklaus Wirth's Modula-2 that he and Telecom engineer Benjamin Kowarsch have developed to address serious software engineering issues of safety, security, reliability, and extensibility. This month we consider the use of Generic templates to reach toward the software engineering grail of reusable code.

Modern programming practice first saw Generics in Modula-3, C++, and Java. The Modula-3 technique was then modified somewhat by the Spy as part of a proposal to the ISO committee for Modula-2 and this became a supplementary standard to that work, subsequently implemented by most vendors.

Generic facilities address two common situations with a lightweight solution for which using class types and their objects is overkill. These are:

1. the implementation of algorithms whose expression is essentially identical across many the data types on which it is used. The classic example is a sorting algorithm, which, once implemented, can be re-used for a new data type by modifying only the way that comparisons and swops are done.

2. the implementation of data structures whose maintenance code is essentially identical across the many data types that may be stored in it. Examples include linked lists, various tree structures, and so on.

In both cases, rather than implement once, then modify to suit alternate data types, it makes sense to have a facility that allows the code to be expressed in a manner that is generic, that is, with a dummy data type present in the code, and a provision to "refine" this generic code for a specified data type by the expedient of passing to a refining utility a pseudo-parameter naming that data type.

ISO Modula-2 generics achieved this by employing a parameterized Generic module pair as compilation units, which could be refined any number of times by the compiler, whenever it was presented with a refining module pair that supplied the actual parameters. One wrote, for instance:

GENERIC DEFINITION MODULE Sorts (Item : TYPE; GenCompare : CompareProc);

FROM Comparisons IMPORT

CompareProc = PROCEDURE (Item, Item) : CompareResults;

PROCEDURE Quick (VAR data : ARRAY OF Item);

(* Other procedures and functions would be included as well. *)
END Sorts.

and then wrote the corresponding implementation module, where comparisons for the purpose of sorting were done naming the formal "GenCompare" name, whose actual value would be passed in as parameter on refinement. One could also name, say, a "GenSwop" routine and refine that as well, although this is unnecessary, as it could be hidden in the generic implementation and be written to swop using the generic type name. Only type parameters and constant value parameters (which includes specific procedure names) were allowed as formal generic module parameters. Note that the type of a formal parameter could be defined in the generic definition itself as the compiler has access to the entire contents of such a definition, and this is a trivial forward reference.
A refining module pair would have:

END CardStack.

and likewise for the refining implementation, with the identical actual parameter(s) required.
It was up to implementors to determine the mechanics of template refinement, but the semantics were to be as if a new separate library module were created from the template with the substitutions per the module parameters.

In R10
we determined that since all that was in view was textual substitution, we might as well be explicit and assume the presence of a utility to handle such substitutions. After all, it could be used for other purposes than template refinement. Thus, we dispense with refining definition and implementation modules, and with module parameters. moreover, since, for instance, comparison can be handled by binding to operators, the sorting example can be simplified. Mo compareProc is needed. Just write the code using the standard comparison operator(s), bind to the operator when defining the ADT, and the correct comparison code will be automatically called.
All items that must be replaced by substitution are enclosed in a double hash. Indeed, R10 specifies a language for templates, illustrated in portions of a template module for static arrays:

DEFINITION MODULE ##ModuleIdent## [ProtoStaticArray];

/* Modula-2 R10 Static Array Type Template */
* All parameters are marked (A) automatic, (M) mandatory or (D) default.
* This template expands the following parameters:
* TemplateVersion (A) -- The date and time stamp of this template,
* automatically set by the template engine utility.
* ModuleIdent (A) -- The library's identifier,
* automatically supplied by the GENLIB directive.
* IndexType (M) -- The index type must be an ordinal type. Compilation of
* the generated library will fail if it is not an ordinal type.
* ValueType (M) -- The value type of the array, THERE IS NO DEFAULT.
* Template expansion will fail if the parameter is omitted.
* LowerBound (D) and UpperBound (D) -- If omitted, the values of TMIN (Inde Type and TMAX(IndexType) will be used.
/* ---------------------------------------------------------------------------
* Placeholder Verification and Defaults
* ------------------------------------------------------------------------ */

/* Define placeholder ADT as an alias of ModuleIdent */
<#DEFINE ADT = @@ModuleIdent@@#>

/* Verify IndexType holds a mixed or uppercase identifier, else fail */
<#VERIFY IndexType [Aa|AA] FAIL#>

/* Verify ValueType holds a mixed or uppercase identifier, else fail */
<#VERIFY ValueType [Aa|AA] FAIL#>

/* If LowerBound is omitted, use TMIN(IndexType) */
<#DEFIF UNDEFINED(LowerBound) : LowerBound = "TMIN(##IndexType##)" #>

/* If UpperBound is omitted, use TMAX(IndexType) */
<#DEFIF UNDEFINED(UpperBound) : LowerBound = "TMAX)(##IndexType##)" #>

IMPORT ##IndexType##
IMPORT ##ValueType##

CONST isOrdered = TRUE;
CONST componentCount = ##UpperBound## - ##LowerBound## + 1;

entry : ARRAY componentCount OF ValueType
END; (* ##ADT## *)

TYPE ValueType = ALIAS OF ##ValueType##;

PROCEDURE [:=] assignStructuredValue
( array : ##ADT##; value : ARGLIST componentCount OF ValueType );

( CONST source : ##ADT##; VAR target : ##ADT## );

PROCEDURE [STORE] storeValueAtIndex
( array : ##ADT##;
index : ##IndexType##; value : ##ValueType## );

( array : ##ADT##; index : ##IndexType## );

PROCEDURE [COUNT] count ( array : ##ADT## ) : LONGCARD;

TYPE ForLoopBodyProc = PROCEDURE ( (* index : *) CONST ##IndexType## );

PROCEDURE [FOR] forIterator
( assocArray : ##ADT##;
forLoopBody : ForLoopBodyProc; ascending : BOOLEAN );

PROCEDURE [=] isEqual
( array1, array2 : ##ADT## ) : BOOLEAN;

/* General IO library */
<#EXPAND "StaticArrays" :
ModuleIdent = @@ADT@@"IO";
ValueType = @@ValueType@@
GenIO = "TRUE"#>

END ##ModuleIdent##.

<#IF GenIO#>
/* Generate the ADT's IO Library */

PROCEDURE [READ] Read ( file : File; VAR array : ##ADT## );

PROCEDURE [WRITE] Write ( file : File; array : ##ADT## );
( file : File; fmtStr : ARRAY OF CHAR;
items : VARIADIC OF ##ADT## );

END ##IOLibrary##.

This template is expanded by the M2 R10 template engine utility. Expansion may be invoked within a compiling source file using the GENLIB directive.

GENLIB FooArray FROM GenStaticArrays FOR
IndexType = "Barbaz";
ValueType = "Bamboo"

and thereafter, the newly generated library may be simply imported into the current or some other scope.

IMPORT FooArray;

During template expansion, any occurrences of ##ModuleIdent## are replaced by the identifier following GENLIB, and any occurences of ##ValueType## are replaced by the quoted value given for ValueType in the GENLIB directive. Template comments (like this one) are removed during template expansion.
In this instance (and likely in many others) the template itself depends on a blueprint. as it contains bindings. Moreover, this template generate two libraries--one for the data structure itself, and a second for its I/O.

This is just a taste of what can be done using templates. But, as we said last month with respect to blueprints, it ought to give the reader some idea of how Modula-2 R10 enforces the discipline of planning to assist in producing sound well-thought-out code, and provides the means to re-use tried and true code frameworks with a variety of other data types.

What about OO?

Wirth's original Modula-2 notation lacked OO. The ISO committee added two object oriented variants in an extension--one garbage collected, the other not. At this point, R10 is a base notation and has no object types. However, this is planned as part of a second phase, likely using the Objective-C philosophy, and for this purpose a few words have been reserved sequestered as probable future reserved words and standard identifiers. We do contend, however, that OO is not the best technique for everything, and at least some tasks often performed using it can be expressed more simply without.

That's all folks so for more information consult the repository site. Next month the Spy returns to his usual perambulations about the technical world, complete with observations on related social, economic, and political issues. Stay tuned, and remember you read it here first.

--The Northern Spy

Opinions expressed here are entirely the author's own, and no endorsement is implied by any community or organization to which he may be attached. Rick Sutcliffe, (a. k. a. The Northern Spy) is professor of Computing Science and Mathematics at Canada's Trinity Western University. He has been involved as a member or consultant with the boards of several community and organizations, and participated in developing industry standards at the national and international level. He is a co-author of the Modula-2 programming language R10 dialect. He is a long time technology author and has written two textbooks and nine alternate history SF novels, one named best ePublished SF novel for 2003. His columns have appeared in numerous magazines and newspapers (paper and online), and he's a regular speaker at churches, schools, academic meetings, and conferences. He and his wife Joyce have lived in the Aldergrove/Bradner area of BC since 1972.

Want to discuss this and other Northern Spy columns? Surf on over to ArjayBB. com. Participate and you could win free web hosting from the WebNameHost. net subsidiary of Arjay Web Services. Rick Sutcliffe's fiction can be purchased in various eBook formats from Fictionwise, and in dead tree form from Amazon's Booksurge.

URLs for Rick Sutcliffe's Arjay Enterprises:

The Northern Spy Home Page: http: //www. TheNorthernSpy. com
opundo : http: //opundo. com
Sheaves Christian Resources : http: //sheaves. org
WebNameHost : http: //www. WebNameHost. net
WebNameSource : http: //www. WebNameSource. net
nameman : http: //nameman. net

General URLs for Rick Sutcliffe's Books:
Author Site: http: //www. arjay. ca
Publisher's Site: http: //www. writers-exchange. com/Richard-Sutcliffe. html
The Fourth Civilization--Ethics, Society, and Technology (4th 2003 ed. ): http: //www. arjay. bc. ca/EthTech/Text/index. html
Sites for Modula-2 resources
Modula-2 FAQ and ISO-based introductory text:
R10 Repository and source code:
The Supplied Blueprint Hierarchy:

More links, Wiki:
p1 ISO Modula-2 for the Mac:


Community Search:
MacTech Search:

Software Updates via MacUpdate

MacFamilyTree 8.2.7 - Create and explore...
MacFamilyTree gives genealogy a facelift: modern, interactive, convenient and fast. Explore your family tree and your family history in a way generations of chroniclers before you would have loved.... Read more
WhatsApp 0.2.8000 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
TotalFinder 1.10.7 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Features... Read more
Box Sync 4.0.7886 - Online synchronizati...
Box Sync gives you a hard-drive in the Cloud for online storage. Note: You must first sign up to use Box. What if the files you need are on your laptop -- but you're on the road with your iPhone? No... Read more
Espresso 5.1 - Powerful HTML, XML, CSS,...
Note from the developer: For the new Espresso, we changed our versioning and licensing approach with more consistent pricing and a simpler development timeline: "X+1". Each new update would increase... Read more
VueScan 9.6.04 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Slack 3.0.5 - Collaborative communicatio...
Slack is a collaborative communication app that simplifies real-time messaging, archiving, and search for modern working teams. Version 3.0.5: Bug Fixes: An important security update. Security... Read more
VirtualBox 5.2.6 - x86 virtualization so...
VirtualBox is a family of powerful x86 virtualization products for enterprise as well as home use. Not only is VirtualBox an extremely feature rich, high performance product for enterprise customers... Read more
Vivaldi 1.13.1008.40 - An advanced brows...
Vivaldi is a browser for our friends. In 1994, two programmers started working on a web browser. Our idea was to make a really fast browser, capable of running on limited hardware, keeping in mind... Read more
WhatRoute 2.1.1 - Geographically trace o...
WhatRoute is designed to find the names of all the routers an IP packet passes through on its way from your Mac to a destination host. It also measures the round-trip time from your Mac to the router... Read more

Latest Forum Discussions

See All

JYDGE (Games)
JYDGE 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: Build your JYDGE. Enter Edenbyrg. Get out alive. JYDGE is a lawful but awful roguehate top-down shooter where you get to build your... | Read more »
Tako Bubble guide - Tips and Tricks to S...
Tako Bubble is a pretty simple and fun puzzler, but the game can get downright devious with its puzzle design. If you insist on not paying for the game and want to manage your lives appropriately, check out these tips so you can avoid getting... | Read more »
Everything about Hero Academy 2 - The co...
It's fair to say we've spent a good deal of time on Hero Academy 2. So much so, that we think we're probably in a really good place to give you some advice about how to get the most out of the game. And in this guide, that's exactly what you're... | Read more »
Everything about Hero Academy 2: Part 3...
In the third part of our Hero Academy 2 guide we're going to take a look at the different modes you can play in the game. We'll explain what you need to do in each of them, and tell you why it's important that you do. [Read more] | Read more »
Everything about Hero Academy 2: Part 2...
In this second part of our guide to Hero Academy 2, we're going to have a look at the different card types that you're going to be using in the game. We'll split them up into different sections too, to make sure you're getting the most information... | Read more »
Everything about Hero Academy 2: Part 1...
So you've started playing Hero Academy 2, and you're feeling a little bit lost. Don't worry, we've got your back. So we've come up with a series of guides that are going to help you get to grips with everything that's going on in the game. [Read... | Read more »
What mobile gaming can learn from the Ni...
While Nintendo might not have had things all its own way since it began developing for mobile, one thing it has got right is the release of the Switch. After the disappointment of the WiiU, which I still can't really explain, the Switch felt a... | Read more »
Programmer of Sonic The Hedgehog launche...
Japanese programmer Yuji Naka is best known for leading the team that created the original Sonic The Hedgehog. He’s moved on from the speedy blue hero since then, launching his own company based in Tokyo – Prope Games. Legend of Coin is the... | Read more »
Why doesn't mobile gaming have its...
The Overwatch League is a pretty big deal. It's an attempt to really push eSports into the mainstream, by turning them into, well, regular sports. But slightly less sweaty. It's a lavish affair with teams from all around the world, and more... | Read more »
Give Webzen’s new billiard game PoolTime...
Best known for producing hugely popular MMO titles, South Korean publisher Webzen is now taking aim at a different genre altogether. PoolTime is a realistic eight ball pool simulator, allowing you to compete in real-time matches against players... | Read more »

Price Scanner via

9.7-inch 2017 WiFi iPads on sale starting at...
B&H Photo has 9.7″ 2017 WiFi #Apple #iPads on sale for $30 off MSRP for a limited time. Shipping is free, and pay sales tax in NY & NJ only: – 32GB iPad WiFi: $299, $30 off – 128GB iPad WiFi... Read more
Wednesday deal: 13″ MacBook Pros for $100-$15...
B&H Photo has 13″ #Apple #MacBook Pros on sale for up to $100-$150 off MSRP. Shipping is free, and B&H charges sales tax for NY & NJ residents only: – 13-inch 2.3GHz/128GB Space Gray... Read more
Apple now offering Certified Refurbished 2017...
Apple has Certified Refurbished 9.7″ WiFi iPads available for $50-$80 off the cost of new models. An Apple one-year warranty is included with each iPad, and shipping is free: – 9″ 32GB WiFi iPad: $... Read more
10″ iPad Pros on sale for $50-$75 off MSRP, n...
B&H Photo has 10″ and #Apple #iPad Pros on sale for up to $75 off MSRP. Shipping is free, and B&H charges sales tax in NY & NJ only. Note that some sale prices are restricted to certain... Read more
Apple refurbished Mac minis available startin...
Apple has restocked Certified Refurbished Mac minis starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: – 1.4GHz Mac mini: $419 $80 off MSRP – 2.6GHz Mac... Read more
Amazon offers Silver 13″ Apple MacBook Pros f...
Amazon has new Silver 2017 13″ #Apple #MacBook Pros on sale today for up to $150 off MSRP, each including free shipping: – 13″ 2.3GHz/128GB Silver MacBook Pro (MPXR2LL/A): $1199.99 $100 off MSRP – 13... Read more
Sale: 12″ 1.3GHz MacBooks on sale for $1499,...
B&H Photo has Space Gray and Rose Gold 12″ 1.3GHz #Apple MacBooks on sale for $100 off MSRP. Shipping is free, and B&H charges sales tax for NY & NJ residents only: – 12″ 1.3GHz Space... Read more
Apple offers Certified Refurbished 2017 iMacs...
Apple has a full line of Certified Refurbished iMacs available for up to $350 off original MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are available: – 27... Read more
13″ MacBook Airs on sale for $120-$100 off MS...
B&H Photo has 2017 13″ 128GB MacBook Airs on sale for $120 off MSRP. Shipping is free, and B&H charges sales tax for NY & NJ residents only: – 13″ 1.8GHz/128GB MacBook Air (MQD32LL/A): $... Read more
15″ Touch Bar MacBook Pros on sale for up to...
Adorama has Space Gray 15″ MacBook Pros on sale for $200 off MSRP. Shipping is free, and Adorama charges sales tax in NJ and NY only: – 15″ 2.8GHz MacBook Pro Space Gray (MPTR2LL/A): $2199, $200 off... Read more

Jobs Board

*Apple* Solutions Consultant - Apple (United...
# Apple Solutions Consultant Job Number: 113384559 Brandon, Florida, United States Posted: 10-Jan-2018 Weekly Hours: 40.00 **Job Summary** Are you passionate about Read more
Art Director, *Apple* Music + Beats1 Market...
# Art Director, Apple Music + Beats1 Marketing Design Job Number: 113258081 Santa Clara Valley, California, United States Posted: 05-Jan-2018 Weekly Hours: 40.00 Read more
*Apple* Pay & Wallet Engineering Manager...
# Apple Pay & Wallet Engineering Manager, Apple Watch Job Number: 83769531 Santa Clara Valley, California, United States Posted: 06-Nov-2017 Weekly Hours: 40.00 Read more
UI Tools and Automation Engineer, *Apple* M...
# UI Tools and Automation Engineer, Apple Media Products Job Number: 113136387 Santa Clara Valley, California, United States Posted: 11-Jan-2018 Weekly Hours: 40.00 Read more
Senior Product Architect, *Apple* Pay - App...
# Senior Product Architect, Apple Pay Job Number: 58046427 Santa Clara Valley, California, United States Posted: 04-Jan-2018 Weekly Hours: **Job Summary** Apple , Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.