<<

Programming in -3 Springer Berlin Heidelberg New York Barcelona Budapest Hong Kong London Milan Paris Santa Clara Singapore Tokyo Laszlo Boszormenyi Carsten Weich

Programming in Modula-3 An Introduction in Programming with Style

Foreword by Joseph Weizenbaum

, Springer Usz16 Boszormenyi Carsten Weich U niversitat Klagenfurt Institutfiir Informatik UniversitatsstraBe 65-67 A-9022 Klagenfurt

With 61 figures

The software environment was created with the kind support of Springer• Verlag, Digital Equipment Corporation, and Raiffeisenverband Karnten

Translated from the German edition Programmieren mit Modula-3 by Robert Bach, Traunkirchen, Austria

ISBN-13: 978-3-642-64614-0 e-ISBN-13: 978-3-642-60940-4 DOl: 10.1007/978-3-642-60940-4

CIP-data applied for Die Deutsche Bibliothek CIP-Einheitsaufnahme programming in Modula-3: an introduction in programming with style / Uszl6 Boszormenyi; Carsten Weich. Foreword by Joseph Weizenbaum [Trans!. from the German ed. by Robert Bach J. - Berlin; Heidelberg; New York; Barcelona; Budapest; Hong Kong; London; Milan; Paris; Santa Clara; Signapore; Tokyo: Springer; 1996 Dt. Ausg. u.d.T.: Boszormenyi. Uszl6: Programmieren mit Modula-3 ISBN-13: 978-3-642-64614-0 NE: Weich. Carsten: This work is subject to copyright. All rights are reserved. whether the whole or part of the material is concerned. specifically the rights oftranslation. reprinting. reuse ofillustrations. recitation. broadcasting. reproduction on microfilm or in other ways. and storage in data banks. Duplication ofthis publication or parts thereofis permiuedonlyunder the provisions of the German Copyright Law of September 9.1965. in its current version. and permission for use must always be obtained from Springer-Verlag. Violations are liable for prosecution act under German Copyright Law. © Springer-Verlag Berlin Heidelberg 1996 Softcover reprint ofthe hardcover 1st edition 1996 The use ofgeneral descriptive names. registered names. trademarks. etc. in this publication does not imply. even in the absence of a specific statement. that such names are exempt from the relevant protective laws and regulations and therefore free for general use. Typesetting: Camera-ready by authors; Cover illustration: Hegedus Miklos Cover design: Klinkel + Lopka Werbeagentur. Ilvesheim SPIN:I0426494 33/3020-543210 - Printed on acid -free paper To Joseph Weizenbaum Foreword by Joseph Weizenbaum

Since the dawn of the age of , people have cursed the difficulty of programming. Over and over again we encounter the suggestion that we should be able to communicate to a in natural language what we want it to do. Unfortunately, such advice rests upon a misconception of both the computer and its task. The computer might not be stupid, but it is stubborn. That is, the computer does what all the details of its pro• gram command it to do, i.e., what the programmer "tells" it to do. And this can be quite different from what the programmer intended. The misun• derstanding with respect to tasks posed to the computer arises from the failure to recognize that such tasks can scarcely be expressed in natural language, if indeed at all. For example, can we practice music, chemistry or mathematics without their respective special symbolic languages? Yet books about computers and programming languages can be written more or less reasonably, even if they are not quite poetic or lyrical. This book can serve as an example of this art and as a model for anyone at• tempting to teach inherently difficult subject matters to others.

Klagenfurt, April 1995 Preface

Striving to make learning to program easier, this book addresses primarily students beginning a computer science major. For our program examples, we employ a new, elegant , Modula-3. However, most of the concepts that we introduce apply and are relevant indepen• dently of the specific programming language. This book can either accompany an introductory lecture on program• ming or serve self-study purposes. Both cases absolutely demand hands-on programming practice in addition to reading the book. Perusing a book on programming in dry dock without ever navigating the challenging waters of programming would be like reading about how to playa violin without ever touching the instrument. Learning to program means mastering both theory and practice, preferably simultaneously. Newcomers to a computer science major bring with them a broad range of different backgrounds. Some have no computer literacy, while others can handle certain application programs such as word processors or spread• sheets. Still others have programming experience, although the breadth and depth of their skills varies greatly. This book assumes no particular prerequisites. A reader armed with normal high school mathematics and rudimentary computer literacy should be able to understand this book. We begin with fundamental concepts and only stepwise introduce the more dif• ficult, higher-level concepts that build on them. To avoid the risk of bore• dom, students with a higher level of programming experience should feel free to skim over exhaustive explanations that are already clear to them.

Organization of the Book

The book consists offive parts:

1. Introduction In the first chapter we cast light on the term programming from var• ious perspectives and show their relative importance in the field of computer science. The second chapter introduces a formal notation for the precise specification of the syntax of programming languages. x

2. Introduction to Programming Chapters 3 to 10 introduce the classical programming concepts. Be• ginning with a sequence of statements and many simple and user• defined static types, these chapters move on to arm the reader with procedures, functions and modules to be able to correctly structure even complex problems. On completion of Chapter 10, the reader should be able to write many challenging programs.

3. Advanced Programming Here we introduce a number of concepts that particularly support the development of program systems that need to react to ever changing sets of data. We present dynamic data structures as well as recur• sion at the algorithmic and data-structure level. The reader also be• comes familiar with persistent data and exception handling. Chapter 13 treats object-oriented programming, which has conquered an ever growing share of the field of software system development. Another steadily rising field, parallel programming, highlights Chapter 16.

4. Appendices Through the appendices we have striven to ease the task of Modula-3 programming. Appendix A describes a complete non-trivial program to manage music CD's. Appendix B, intended as a reference for the pros, offers a complete but very compact description of the semantics of Modula-3. It is a reprint of the original Modula-3 language defini• tion [CDG+S9]. Further appendices describe the most important in• terfaces to the Modula-3 development environment and provide con• cise descriptions of various such environments. The appendices also include detailed instructions on installing and configuring a Modula-3 development environment and the software included with this book.

5. Included Software All examples in the book have been tested. They are either executable themselves or parts of executable programs. We provide these to the reader at no charge. All Modula-3 programs (including the Modula-3 ) can be started from an integrated, interactive, user-friendly environment.

Acknowledgments Our foremost gratitude goes to Roland Mittermeir, who profoundly con• tributed to the production of this book. Significant texts and examples in Chapters 10 to 12 come from him. He is actually a co-author of this book. We also owe special thanks to Hans-Peter Mossenbock, Peter Rechen• berg, Johann Eder and Karl-Heinz Eder; they assumed the enormously Xl work-intensive and thankless task of thoroughly proofreading the origi• nal German manuscript. We likewise wish to express our gratitude to Michael Dobrovnik for his comments on our example program in the ap• pendix. Their criticisms and comments taught us a great deal, and without their contributions it would have been impossible to complete this book. Naturally the authors retain full and sole accountability for any errors. Our gratitude also goes to the researchers at Digital Systems Research Center, Palo Alto, who developed Modula-3 and made it available. We es• pecially thank Marc Najork, for his support. We are also grateful to Greg Nelson and Bill Kalsow. We also extend our appreciation to Springer-Verlag, Digital Equipment Corporation, the University of Klagenfurt and the Raiffeisen Bank of Ca• rinthia for their generous support of the development of our user-friendly Modula-3 environment and to Miklos Szabo for his development work. We also offer our sincere thanks to Silvia Nedizavec for her meticulous preparation of the figures in this book and to Michael Vrbicky for his help in formatting the English edition. Last but not least, we thank our patient families, who spent many evenings and weekends without us during the two years in which we wrote this book. We offer the reader this book as the fruits of our labors in the hope that it proves to be a useful learning instrument and that it provides some fun and pleasure along the way. Contents

1 What is programming? 1 1.1 An informal introduction. 1 1.1.1 Algorithms ..... 2 1.1.2 Switches and symbols 4 1.1.3 Turing machine ... . 6 1.1.4 Computability .... . 7 1.2 The von Neumann computer. 9 1.3 Rigid thought structures ... 11 1.4 Programming in the small . . 14 1.4.1 Software production methods 14 1.4.2 Writing simple programs ... 17 1. 5 Levels of programming ...... 18 1.5.1 Formal and human languages. 18 1.5.2 Assembler ...... 20 1.5.3 High-level programming languages. 21 1.6 Programming and computer science .... 24 1.6.1 The responsibility of computer scientists 25

2 Metalanguages 27 2.1 Definition of formal languages . 27 2.2 Digits and numbers . . 29 2.3 Names ...... 30 2.4 Arithmetic expressions . . . . . 31 2.5 Extension for Modula-3 syntax 33

3 The structure of programs 35 3.1 Structuring ...... 35 3.2 Language environment ...... 36 3.3 The statics and dynamics of a program . 38 3.3.1 Data and data types .... 39 3.3.2 Algorithms and procedures 41 3.4 Structure of Modula-3 programs 42 3.4.1 The module ...... 42 XlV Contents

3.4.2 Hello, world ...... 44 3.4.3 Source code ...... 46 3.4.4 Computing the arithmetic mean 47 3.4.5 SIO interface...... 50

4 Predefined data types 53 4.1 Integers ...... 53 4.1.1 Range .. . 53 4.1.2 Operations 54 4.2 Logical type ... 60 4.2.1 Range... 60 4.2.2 Operations 60 4.3 Characters . . . . 63 4.3.1 Range ... 63 4.3.2 Operations 65 4.4 Texts ...... 67 4.4.1 Range .. . 67 4.4.2 Operations 68 4.5 Floating-point numbers. 72 4.5.1 Range ...... 73 4.5.2 Floating-point literals 74 4.5.3 Operations ...... 75 4.5.4 Input and output of floating-point numbers 78

5 Statements 83 5.1 The assignment 83 5.2 Structured statements 84 5.3 Sequence ...... 87 5.4 Branches ...... 87 5.4.1 If statement .. 87 5.4.2 Case statement 92 5.4.3 Equivalence of If and Case . 96 5.5 Loops ...... 97 5.5.1 While loop .. . 97 5.5.2 Loop invariants 102 5.5.3 Repeat loop. . . 105 5.5.4 For loop ..... 108 5.5.5 Loop statement 110 5.5.6 Equivalence of the repetition statements 112

6 User-defined simple types 115 6.1 Enumeration ...... 115 6.1.1 Predefined enumerations. 117 Contents xv

6.1.2 Range ... 117 6.1.3 Operations 118 6.2 Subranges .... 120 6.2.1 Operations 122 6.2.2 Predefined subranges . 122

7 Expressions and declarations 125 7.1 Expressions ...... 125 7.1.1 Syntax of expressions ... 125 7.1.2 Evaluation of expressions 127 7.1.3 Evaluation oflogical expressions 128 7.2 Declarations ...... 129 7.2.1 Constant declarations 129 7.2.2 Type declarations .. 131 7.2.3 Variable declarations 132 7.3 Equivalence of types ... 133 7.4 Subtypes ...... 134 7.5 Assignment compatibility 135 7.6 Expression compatibility 136

8 Composite static types 139 8.1 Arrays ...... 140 8.1.1 Unidimensional arrays .. 141 8.1.2 Multidimensional arrays. 142 8.1.3 Array constructors 144 8.1.4 Operations on arrays .. . 145 8.1.5 Example: Schedule ... . 148 8.1.6 Linear search in an array 150 8.1.7 Sorting an array. 152 8.2 Records ...... 154 8.2.1 Record selectors .. . 156 8.2.2 Record constructors . 157 8.2.3 Operations with records 160 8.2.4 With statement . . . . . 160 8.2.5 Example: Student data management. 162 8.3 Sets ...... 163 8.3.1 Range ...... 164 8.3.2 Set constructors .. 165 8.3.3 Operations on sets 165 8.3.4 Example: Input of numbers 168 8.4 Comparison of arrays, records and sets. 170 8.5 Packed data types ...... 170 XVI Contents

9 Structuring algorithms 173 9.1 Block structure ...... 173 9.2 Procedures and functions .. . 177 9.2.1 Procedure declaration 179 9.2.2 Procedure invocation 181 9.3 Modes of parameter passing 183 9.3.1 Value parameter ... 185 9.3.2 Variable parameters 185 9.3.3 Read-only parameters 186 9.3.4 Information transfer via global variables 187 9.3.5 Comparing the kinds of parameters 188 9.4 IdentifYing the procedures .... 192 9.5 Name, type and default value of a parameter . . 193 9.6 Eval statement ...... 194 9.7 Procedure types ...... 195 9.7.1 Operations with procedures 195

10 Modules 201 10.1 Structure ...... 206 10.1.1 Interface .... 207 10.1.2 Implementation 208 10.1.3 Compilation units. 210 10.2 Using modules ...... 210 10.2.1 Structuring the data space . 212 10.2.2 Type creation ...... 215 10.2.3 Creating toolboxes .... . 219 10.3 An example with graphic elements 219 10.4 Modularization ...... 223

11 Dynamic data structures 227 11.1 Dynamism in static data structures 228 11.1.1 Implementation of stacks as arrays. 228 11.1.2 FIFO queues in arrays ...... 231 11.1.3 Example: Rotating shifts ...... 234 11.1.4 Explicit address management with pointers. 235 11.1.5 Address management by the system 238 11.2 Dynamic data in Modula-3 ..... 241 11.2.1 Allocation and de allocation 241 11.2.2 Operations with references 245 11.2.3 Open (dynamic) arrays 246 11.2.4 Arrays of references . 247 11.3 Subtypes ...... 248 Contents XVll

11.3.1 Subtype rule for references .. 249 11.3.2 Subtype rule for arrays . . . . . 250 11.4 Abstract and encapsulated data types 251 11.4.1 Opaque data types ...... 252 11.4.2 Revelation ...... 254 11.4.3 An abstract and a generic stack. 257 11.4.4 Rules for the design of encapsulated data types 260 11.5 Dynamic structures. 261 11.5.1 Lists...... 262 11.5.2 Kinds oflists ...... 263 11.5.3 Singly linked, sorted linear list 264

12 Recursion 271 12.1 Recursive algorithms ...... 273 12.1.1 Fundamentals of recursive programming 273 12.1.2 Using recursion . . . 278 12.1.3 Quicksort...... 281 12.1.4 The Towers of Hanoi . . . . 282 12.1.5 Recursive list management 285 12.2 Recursive data structures . . . . . 287 12.2.1 Trees ...... 287 12.2.2 Binary trees and search trees 290 12.2.3 Binary search trees ...... 292 12.2.4 Traversing a tree ...... 294 12.2.5 Implementation of the binary search tree 296

13 Objects 305 13.1 Object-oriented modeling. 305 13.2 Object-oriented programming 308 13.2.1 Encapsulation 308 13.2.2 Inheritance. . . . 309 13.2.3 Polymorphism . . 310 13.2.4 Dynamic binding 310 13.2.5 Object-oriented applications . 311 13.3 Object types in Modula-3 . . . . . 312 13.3.1 Declaration of object types . 313 13.3.2 Implementation of objects . 314 13.3.3 Implementation of methods 315 13.3.4 Accessing object components. 317 13.3.5 Creating objects ...... 317 13.3.6 Subtyping rules for objects. 318 13.4 Encapsulation of object types 319 13.4.1 Inheritance...... 323 XVlll Contents

13.4.2 Polymorphism and dynamic binding 325 13.4.3 Generalization ...... 328 13.4.4 The tree class hierarchy . 339 13.4.5 Subclasses of binary trees 344

14 Persistent data structures 349 14.1 Files ...... 350 14.1.1 Accessing files .. 350 14.1.2 Access functions. 351 14.1.3 Files and main memory 352 14.1.4 File types ...... 352 14.2 Files in Modula-3 ...... 353 14.2.1 Input and output streams 353 14.2.2 Fmt and Scan 357 14.2.3 Simple-IO ... 360 14.3 Persistent variables .. 362 14.3.1 Implementation 364

15 Exception handling 371 15.1 Exceptions in a program ...... 371 15.2 Exception handling in Modula-3 .. 375 15.2.1 Exceptions, run-time errors, programming errors ... 375 15.2.2 Declaration of exceptions. 376 15.2.3 Generation of exceptions 376 15.2.4 Exception handling .. 376 15.2.5 Delegating exceptions . 377 15.3 Delaying exception handling . . 379 15.4 Strategies for exception handling 382

16 Parallel programming 385 16.1 Motivation for parallelism 385 16.2 Parallel programs .... . 388 16.3 Threads in Modula-3 .. . 390 16.3.1 Schedulers ofModula-3 environments 390 16.3.2 Creating threads ..... 391 16.4 Shared variables...... 397 16.4.1 Data-parallel algorithms ...... 397 16.4.2 Critical regions and mutual exclusion 400 16.4.3 Type Mutex and the Lock statement 402 16.4.4 Monitor ... 405 16.4.5 Semaphores 413 16.5 Message passing .. 418 Contents XIX

16.5.1 Client/server model ...... 418 16.5.2 Synchronous message communication 419 16.5.3 Asynchronous message communication 419 16.5.4 Channels ...... 420

A A small database 427 Al The task ... · ...... 427 The object model...... 428 A3 Interfaces of the object model 431 A3.1 Interface of the base object. 431 A3.2 The specific interfaces 432 A4 · ... 433 A4.1 Input strategy 433 A4.2 Output · ... 435 A5 Implementation ... 436 A5.1 Persistent sets . 437 A5.2 Sets · ...... 438 A5.3 Object lists ... 439 A5.4 Auxiliary modules . 439 A5.5 Selections...... 439 A5.6 Implementation modules of the object model 440 A5.7 Input 441 A5.8 Queries ...... 442 A6 Interfaces ...... 443 A7 Implementation modules . 447

B Language Definition 469 B.l Definitions · ... 469 B.2 Types ...... 470 B.2.1 Ordinal types 470 B.2.2 Floating-point types 471 B.2.3 Arrays · ... 472 B.2.4 Records .... 473 B.2.5 Packed types . 474 B.2.6 Sets · ... 474 B.2.7 References 474 B.2.8 Procedures 475 B.2.9 Objects · . 477 B.2.10 Subtyping rules 480 B.2.11 Predeclared opaque types 482 B.3 Statements ...... 482 B.3.1 Assignment 483 B.3.2 Procedure call 484 xx Contents

B.3.3 Eval ...... 485 B.3A Block statement .... . 486 B.3.5 Sequential composition . 486 B.3.6 Raise .... 486 B.3.7 Try Except . 487 B.3.8 Try Finally . 488 B.3.9 Loop .. 488 B.3.10 Exit .. 488 B.3.11 Return 489 B.3.12 If .... 489 B.3.13 While 490 B.3.14 Repeat 490 B.3.15 With. 490 B.3.16 For ... 491 B.3.17 Case . . 492 B.3.18 Typecase 492 B.3.19 Lock ... 493 B.3.20 Inc and Dec 493 BA Declarations . . . 494 BA.1 Types ... 494 BA.2 Constants 494 BA.3 Variables 495 BAA Procedures 495 B.4.5 Exceptions 496 B.4.6 Opaque types 496 BA.7 Revelations. . 496 BA.8 Recursive declarations 497 B.5 Modules and interfaces .. 498 B.5.1 Import statements 499 B.5.2 Interfaces. 500 B.5.3 Modules ... 500 B.5A Generics . . . 501 B.5.5 Initialization. 503 B.5.6 Safety. . . . . 503 B.6 Expressions ..... 504 B.6.1 Conventions for describing operations 504 B.6.2 Operation syntax 505 B.6.3 Designators ...... 506 B.6A Numeric literals ...... 507 B.6.5 Text and character literals. 508 B.6.6 Nil ...... 508 B.6.7 Function application ... . 508 B.6.8 Set, array, and record constructors 508 Contents XXI

B.6.9 New ...... 509 B.6.10 Arithmetic operations 510 B.6.11 Relations ...... 513 B.6.12 Boolean operations 514 B.6.13 Type operations .. 514 B.6.14 Text operations .. 516 B.6.15 Constant Expressions. 516 B. 7 Unsafe operations 516 B.8 Syntax ...... 518 B.8.1 Keywords ...... 518 B.8.2 Reserved identifiers . 518 B.8.3 Operators. 518 B.8.4 Comments ...... 518 B.8.5 Pragmas ...... 518 B.8.6 Conventions for syntax . 519 B.8.7 Compilation unit productions 519 B.8.8 Statement productions . 520 B.8.9 Type productions ..... 521 B.8.10 Expression productions .. 521 B.8.11 Miscellaneous productions 522 B.8.12 Token productions. 522

C Library interfaces 525 C.1 Standard interfaces 525 C.l.1 Text .. 525 C.l.2 527 C.l.3 Word 528 C.1.4 Real .. 530 C.l.5 Float 530 C.l.6 FloatMode 533 C.2 Formatting . 534 C.2.1 Fmt ... . 534 C.2.2 Scan ... . 538 C.3 Input and output streams 538 C.3.1 Rd ...... 538 C.3.2 Wr ...... 540 C.3.3 Simple input/output (SIO) 542 C.3.4 Simple Files (SF) ..... 545

D Modula-3 language environments 547 D.1 The DEC/SRC language environment 547 D.2 A language environment for PCs 548 D.2.1 Installation ...... 548 XXII Contents

D.2.2 The programming editor . 549 D.2.3 The browser ...... 550 D.2.4 A 550 D.2.5 Restrictions ...... 551

Bibliography 553

Index 557