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

BetterTouchTool 2.422 - Customize multi-...
BetterTouchTool adds many new, fully customizable gestures to the Magic Mouse, Multi-Touch MacBook trackpad, and Magic Trackpad. These gestures are customizable: Magic Mouse: Pinch in / out (zoom... Read more
VLC Media Player 3.0.1 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Dash 4.1.6 - Instant search and offline...
Dash is an API documentation browser and code snippet manager. Dash helps you store snippets of code, as well as instantly search and browse documentation for almost any API you might use (for a full... Read more
OfficeTime 1.8.2 - Easy time and expense...
OfficeTime is time and expense tracking that is easy, elegant and focused. Other time keepers are clumsy or oversimplified. OfficeTime balances features and ease of use, allowing you to easily track... Read more
OmniOutliner Essentials 5.3 - Organize y...
OmniOutliner Essentials (was OmniOutliner) is a flexible program for creating, collecting, and organizing information. Give your creativity a kick start by using an application that's actually... Read more
OmniOutliner Essentials 5.3 - Organize y...
OmniOutliner Essentials (was OmniOutliner) is a flexible program for creating, collecting, and organizing information. Give your creativity a kick start by using an application that's actually... Read more
OfficeTime 1.8.2 - Easy time and expense...
OfficeTime is time and expense tracking that is easy, elegant and focused. Other time keepers are clumsy or oversimplified. OfficeTime balances features and ease of use, allowing you to easily track... Read more
Dash 4.1.6 - Instant search and offline...
Dash is an API documentation browser and code snippet manager. Dash helps you store snippets of code, as well as instantly search and browse documentation for almost any API you might use (for a full... Read more
Civilization VI 1.1.0 - Next iteration o...
Sid Meier’s Civilization VI is the next entry in the popular Civilization franchise. Originally created by legendary game designer Sid Meier, Civilization is a strategy game in which you attempt to... Read more
Network Radar 2.3.3 - $17.99
Network Radar is an advanced network scanning and managing tool. Featuring an easy-to-use and streamlined design, the all-new Network Radar 2 has been engineered from the ground up as a modern Mac... Read more

Latest Forum Discussions

See All

Construction Simulator 2 reaches its fir...
Construction Simulator 2 debuted iOS and Android devices exactly one year ago, and publisher Astragon is marking the game’s first anniversary with a range of time-limited discounts. It’s been a successful debut for the civil engineering sim, which... | Read more »
All the best games on sale for iPhone an...
This week's list of games on sale for the iPhone and iPad isn't too bad really. There's some gems on here, as well as some games that have had their prices cut low enough that you can look past the rough edges and questionable decisions. [Read... | Read more »
The best games that came out for iPhone...
It's not a huge surprise that there's not a massive influx of new, must-buy games on the App Store this week. After all, GDC is happening, so everyone's busy at parties and networking and dying from a sinister form of jetlag. That said, there are... | Read more »
Destiny meets its mobile match - Everyth...
Shadowgun Legends is the latest game in the Shadowgun series, and it's taking the franchise in some interesting new directions. Which is good news. The even better news is that it's coming out tomorrow, so if you didn't make it into the beta you... | Read more »
How PUBG, Fortnite, and the battle royal...
The history of the battle royale genre isn't a long one. While the nascent parts of the experience have existed ever since players first started killing one another online, it's really only in the past six years that the genre has coalesced into... | Read more »
Around the Empire: What have you missed...
Oh hi nice reader, and thanks for popping in to check out our weekly round-up of all the stuff that you might have missed across the Steel Media network. Yeah, that's right, it's a big ol' network. Obviously 148Apps is the best, but there are some... | Read more »
All the best games on sale for iPhone an...
It might not have been the greatest week for new releases on the App Store, but don't let that get you down, because there are some truly incredible games on sale for iPhone and iPad right now. Seriously, you could buy anything on this list and I... | Read more »
Everything You Need to Know About The Fo...
In just over a week, Epic Games has made a flurry of announcements. First, they revealed that Fortnite—their ultra-popular PUBG competitor—is coming to mobile. This was followed by brief sign-up period for interested beta testers before sending out... | Read more »
The best games that came out for iPhone...
It's not been the best week for games on the App Store. There are a few decent ones here and there, but nothing that's really going to make you throw down what you're doing and run to the nearest WiFi hotspot in order to download it. That's not to... | Read more »
Death Coming (Games)
Death Coming Device: iOS Universal Category: Games Price: $1.99, Version: (iTunes) Description: --- Background Story ---You Died. Pure and simple, but death was not the end. You have become an agent of Death: a... | Read more »

Price Scanner via

Use your Education discount this weekend to b...
Purchase a new Mac using Apple’s Education discount, and take up to $400 off MSRP. All teachers, students, and staff of any educational institution with a .edu email address qualify for the discount... Read more
15″ 2.2GHz MacBook Pro, certified refurbished...
Apple has Certified Refurbished 15″ 2.2GHz Retina MacBook Pros available for $1699. That’s $300 off MSRP for this model, and it’s the lowest price available for a 15″ MacBook Pro currently offered by... Read more
Clearance 2016 15″ MacBook Pros, certified re...
Apple has Certified Refurbished 2016 15″ Touch Bar MacBook Pros available starting at $1849, up to $690 off original MSRP. An Apple one-year warranty is included with each model, and shipping is free... Read more
Apple restocks clearance 2016 13-inch MacBook...
Apple has Certified Refurbished 2016 13″ MacBook Airs available starting at $809. An Apple one-year warranty is included with each MacBook, and shipping is free: – 13″ 1.6GHz/8GB/128GB MacBook Air: $... Read more
Thursday roundup of the best 13″ MacBook Pro...
B&H Photo has new 2017 13″ MacBook Pros on sale for up to $200 off MSRP. Shipping is free, and B&H charges sales tax for NY & NJ residents only. Their prices are the lowest available for... Read more
Sale: 9.7-inch 2017 WiFi iPads starting at $2...
B&H Photo has 9.7″ 2017 WiFi Apple iPads on sale for $40 off MSRP for a limited time. Shipping is free, and pay sales tax in NY & NJ only: – 32GB iPad WiFi: $289, $40 off – 128GB iPad WiFi: $... Read more
Roundup of Certified Refurbished iPads, iPad...
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
Back in stock! Apple’s full line of Certified...
Save $300-$300 on the purchase of a 2017 13″ MacBook Pro today with Certified Refurbished models at Apple. Apple’s refurbished prices are the lowest available for each model from any reseller. A... Read more
Wednesday deals: Huge sale on Apple 15″ MacBo...
Adorama has new 2017 15″ MacBook Pros on sale for $250-$300 off MSRP. Shipping is free, and Adorama charges sales tax in NJ and NY only: – 15″ 2.8GHz Touch Bar MacBook Pro Space Gray (MPTR2LL/A): $... Read more
Apple offers Certified Refurbished Series 3 A...
Apple has Certified Refurbished Series 3 Apple Watch GPS models available for $50, or 13%, off the cost of new models. Apple’s standard 1-year warranty is included, and shipping is free. Numerous... Read more

Jobs Board

Lead *Apple* Solution Consultant - Apple (U...
# Lead Apple Solution Consultant Portland OR Job Number: 113593449 Portland, Oregon, United States Posted: 20-Mar-2018 Weekly Hours: 40.00 **Job Summary** As a Lead Read more
Senior Linux Systems Engineer, *Apple* Pay...
# Senior Linux Systems Engineer, Apple Pay Job Number: 113584532 Santa Clara Valley, California, United States Posted: 20-Mar-2018 Weekly Hours: 40.00 **Job Read more
Threat Intelligence Engineer - *Apple* Info...
# Threat Intelligence Engineer - Apple Information Security Job Number: 113023220 Austin, Texas, United States Posted: 20-Mar-2018 Weekly Hours: 40.00 **Job Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Manager - Retail Manager - Apple, In...
Job Description:Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as an Apple Retail Manager, you're a master of them Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.