diff --git a/README.md b/README.md index d273b14..297c84a 100644 --- a/README.md +++ b/README.md @@ -3,24 +3,24 @@ Simula语言教程以及中文翻译项目 ———————————————————————————————————————— -###关于 +### 关于 Simula语言是面向对象的鼻祖语言,出于兴趣,出去对翻译技术文档的热情,我决定整理一下这个语言的教程并进行翻译。也希望想练习英文、想试试看翻译技术文档、想提高英文水平的同学一起来参与这个项目,最后的翻译结果大家都可以相互review,相互学习。 原文地址: [An Introduction to Programming in Simula](http://www.macs.hw.ac.uk/~rjp/bookhtml/) by Rob Pooley -###线上预览地址 +### 线上预览地址 [Simula语言教程](http://fkysly.github.io/learn-simula) -###如何运行和开发 +### 如何运行和开发 1. 安装gitbook-cli,利用它安装gitbook v2.2.0。(也可以不看效果,照着英文版本的直接翻译就行了。) 2. 根目录下运行gitbook serve,可以开启本地服务器,访问http://localhost:4000,可以看到效果。(也可以不看效果,照着英文版本的直接翻译就行了。) 3. 根目录下运行gitbook build,可以构建项目,会生成_book目录,可以进行部署。 4. 根目录下运行gulp或者gulp deploy,可以部署到git的远程仓库下的gh-pages分支。(如果你fork,那么是你自己的git远程仓库地址哦) 5. 部署完毕之后,打开http://(your_name).github.io/(repo_name)即可访问。 -###如何参与 +### 如何参与 1. 请先自行学习gitbook的相关知识。 2. fork此项目到自己的账号下。 @@ -30,6 +30,6 @@ Simula语言是面向对象的鼻祖语言,出于兴趣,出去对翻译技 (请注意一点,{{ book.ChapterX }} 相应改为 {{ book.zh-ChapterX }}, {{ book.AppendixX }} 相应改为 {{ book.zh-AppendixX }}) 6. 翻译完毕,请直接pull request到此目录的master。 -###Licence +### Licence licence请参阅en/README.md的内容。 diff --git a/en/Chapter1/README.md b/en/Chapter1/README.md index bae96f1..a7085f1 100644 --- a/en/Chapter1/README.md +++ b/en/Chapter1/README.md @@ -1,8 +1,8 @@ -#Chapter 1 +# Chapter 1 -##begin at the beginning...... +## begin at the beginning...... -###What is a computer program? +### What is a computer program? A computer program (program is always spelt in the American way) is a series of instructions which contains all the information necessary for a computer to perform some task. It is similar to a knitting pattern, a recipe or a musical score. Like all of these it uses a special shorthand, known in this case as a programming language. This book describes how to write and understand programs written in the language SIMULA. The definition used is the 1985 SIMULA Standard, which extends and clarifies the language previously known as SIMULA 67. The 67 stood for 1967, the year in which this earlier version was first defined. @@ -40,7 +40,7 @@ Although the programs shown in this book use bothcapital letters, which are know So we have to put begin and end. What about the text in between? This is made up of instructions to the SIMULA system, which are of two types; DECLARATIONS and STATEMENTS. There are also pieces of the text which are ignored by the SIMULA system and which simply help any human who reads the program to follow what is happening. These are called comments. -###Declarations +### Declarations In example 1.1, the first instruction after the word begin is a declaration: @@ -76,7 +76,7 @@ or, alternatively, by writing etc. which many people find neater. This style is called a declaration list, with a series of identifiers of locations with the same type separated by commas. -###Comments +### Comments The next line is a comment. It begins with the keyword comment, is followed by some text and ends in a semi-colon. @@ -87,7 +87,7 @@ As well as forming lines on their own, comments can also be used in certain plac When you are writing programs in independent sections, as we will be, you may not look back at a "working" component for some time. It is also possible that someone else may need to change what you have written. The design of the overall system should tell him what the component is supposed to do, but the details of how it works may not be obvious. To help everyone understand your programs, you should include comments in them. -###Statements +### Statements The other instructions in our example are all statements. They tell the SIMULA system what it is to do. We shall be looking at the different sorts of statements which exist in SIMULA in detail later. For the moment, let us look briefly at those in the example to get a flavour of the possibilities. @@ -100,7 +100,7 @@ The final statement uses OutImage. Like OutInt, OutImage is a procedure and is a OutImage causes the line which is currently being created - the current image - to be written to the printer or terminal and a new line to be started. You have probably noticed that it does not have any parentheses or numbers after it. These numbers, known as "parameters", are only present when the procedure needs information from the program to carry out its task. -###What do we do with our program? +### What do we do with our program? So now we have what we think is a legal SIMULA program. Unfortunately it is on paper and whilst we know what it should cause to happen, the SIMULA system cannot read from the page. How then do we get the SIMULA system to obey our program? The first step is to write our program, known in full as the "source program", in some medium which the computer housing the SIMULA system can manipulate. Older machines may require you to punch the text on paper tape or cards, but today most machines will handle text files. These are stored in the computer's memory on some magnetic medium such as a disk or tape. You can usually create them by typing them into the system using a text editor. You will need to check the documentation for the computer that you intend to use, especially the SIMULA user's guide or programmer's reference manual. @@ -119,7 +119,7 @@ The final product of compilation and linking is a translation of your original S Note: The ability to compile and run SIMULA programs depends on having access to a computer with a SIMULA system. If your computer currently does not, you may be able to buy one, but they are not available for all computers. The suppliers of those systems known to the author are listed at the back of this book. If your computer is not listed, write to SIMULA A.S., who may be able to help. Their address is given in the list. Readers in the United Kingdom might wish to contact the author. -###Summary +### Summary Each chapter will end with a brief summary of what the author thinks you should have learned from it. In this chapter we have looked informally at what a program and a block are. We used a very simple program, made up of only one block to illustrate this. @@ -132,7 +132,7 @@ Lastly we looked at how to compile and run our program on a computer. {{ book.Chapter2 }} -###Exercises +### Exercises When the author was learning to write programs, he was told the most important rule, "There is no such thing as an armchair programmer". The simplest exercise can often teach even an experienced programmer something new. Avoid the temptation to miss out examples as they will often lead on to the material covered in the next chapter. This chapter has introduced a lot of ideas. You may feel completely bewildered. Do not despair. By using the ideas in successive chapters and examples you will soon become familiar with them. To start with try three fundamental, but by no means unimportant, exercises. @@ -147,4 +147,4 @@ This chapter has introduced a lot of ideas. You may feel completely bewildered. 2. leaving out one of the semi-colons, 3. adding in the extra declarations shown in this chapter. 4. swapping lines around, especially moving begin, end and the declaration of Int1. -Note carefully the differences in messages from the compiler and when running the program in each case. See if the listing is different when messages are printed by the compiler. \ No newline at end of file +Note carefully the differences in messages from the compiler and when running the program in each case. See if the listing is different when messages are printed by the compiler. diff --git a/en/Chapter10/README.md b/en/Chapter10/README.md index 404b4ba..cb218b3 100644 --- a/en/Chapter10/README.md +++ b/en/Chapter10/README.md @@ -1,8 +1,8 @@ -#Chapter 10 - Make me a list +# Chapter 10 - Make me a list -##Lists 1 - Arrays and simple linked lists +## Lists 1 - Arrays and simple linked lists -###Storing lists +### Storing lists In setting exercises 9.3 and 9.4, I hoped to focus your attention on the need to hold lists in ways which are easy to access. Many programs need to read, update and write out long series of data items. These items are the objects which we wish to manipulate. It is rarely worthwhile to use a computer to process one or two items. Even our program which wrote only a few copies of one label used an object with a list of data items within it. The use of files allows us to read lists from outside the program and to store them at its end. Unfortunately, as our updating programs show, it is not a good idea to create a new file, external to the program, each time we add, delete or modify an item in a list. We soon end up with a multitude of out of date files. @@ -11,7 +11,7 @@ The use of objects defined by classes allows us to hide a number of basic items This chapter is the first of three dealing with the handling of lists. It provides simple but elegant mechanisms for solving most of the problems mentioned above. Let us start with the problem of holding a long list of items, which are all of the same type. -###The letter program revisited +### The letter program revisited The text of a letter can be represented as a list of SIMULA text objects, with a maximum number of characters in each. So far, the only way we have seen to hold them is as a list of text declarations, one for each line. This leads to a very long winded program and you probably confined your answer to exercise 9.3 to letters with only a few lines. A much simpler and more concise way of representing the same thing is to declare a single identifier, representing a numbered list of text references. Such an identifier represents an object known as an array of texts. Example 10.1 shows the use of an array in a much simplified letter program, where no addresses are allowed for, only the text and the name of the sender. @@ -67,7 +67,7 @@ Example 10.1: Letter program using a text array. new Leter.WriteLetter end**of**program -###Simple array declarations +### Simple array declarations The syntax of an array declaration is the type specifier of the items in the list (integer, ref(Leter) etc.), followed by the keyword array, followed by an identifier, followed by the "bounds" of the list, enclosed in parentheses. Spaces (or ends of line) are used to separate keywords and identifiers as usual. They are not required between the identifier and the left parenthesis, but may be used if you wish. It is legal to omit the type specifier, in which case the array is asumed to be of type real. @@ -84,7 +84,7 @@ Note that the value of the first bound does not have to be 1. The bounds can hav Note also that the values of the bounds may be given as real values. In this case they are converted to integers in the same way as for assignments. The values can be arithmetic expressions as well as constants. The normal rules for evaluating expressions apply. -###Using array elements +### Using array elements The items in an array list are often called its "elements". Example 10.1 shows how an individual element of Line can be accessed. This is known as a subscripted variable. The value within the parentheses is called the subscript or the index. Item number Len of the list is accessed in ReadLetter. It is referred to as Line(Len). Since Len is increased by one before each Image is copied to Line(Len) the effect is to copy successive lines of input into successive elements of the text array Line. @@ -99,12 +99,12 @@ A subscripted variable may be used wherever a simple variable of the same type m The value of the subscript, converted to an integer if necessary, must lie between the values of the lower and upper bounds, inclusive. If it is outwith this range a runtime error will be reported. -###Notes on differences amongst SIMULA systems +### Notes on differences amongst SIMULA systems Some older SIMULA systems may require square brackets, [ and ], instead of parentheses, ( and ). Programs written for such machines may require changes to compile on up to date systems and vice versa. Some compilers will accept either form, which requires even greater care when moving programs. The lowest permitted value for the lower bound, the highest permitted value for the upper bound and the maximum total number of items permitted in an array are all likely to be different on different systems. The maximum number of elements in an array of one type may also be different from that of another type, even on the same system. Check the Programmers' Reference Manual or Users' Guide for the system you are using. -###Variable length lists +### Variable length lists Clearly the use of arrays allows large amounts of data to be held in locations declared within our programs, without the continual need to access files and without declaring long lists of identifiers. The use of loops, especially for loops, allows us to handle arrays in concise and clear ways. One problem with the use of arrays is that we must tell the system in their declarations how many elements they contain and what their bounds are. Often this may not be known until runtime. This means that example 10.1 can only cope with letters of up to sixty lines. If someone wanted to use the program for a longer letter, they would have to alter the source and recompile it. @@ -174,7 +174,7 @@ Example 10.4: Dynamic array bounds in a class. if Cl1Ref.BoolArr(5) then OutText("True") else OutText("False"); OutImage end**of**program -###A more practical use of dynamic arrays +### A more practical use of dynamic arrays Let us return to our general text processing system. It has been some time since we looked at it, but I hope the features introduced since then have been suggesting solutions to the problems we were facing. In particular, I hope the use of classes and object oriented programming has seemed relevant. This section shows how the combination of class objects and arrays can help the design of the Book level of our program. What we are going to try to do is to design a class Book, with the necessary data structures and procedures for manipulating them. Consider example 10.5. @@ -272,7 +272,7 @@ Example 10.5: Class Book and the accompanying program block. OutImage; new Book(InInt) end**of**main**program -###Top down again +### Top down again Example 10.5 shows how object oriented programming makes top down design easier. Only the skeletons of the components of Book are provided, yet its own actions can be fully defined in terms of these. Actions to be performed on one component can be made into local procedures within the class corresponding to that component. The detail of how such procedures will work can be left until that class is itself considered in detail. This leads to the following description of top down, object oriented design. @@ -281,14 +281,14 @@ The visible properties of each component are defined by the operation of the obj Even simpler is, Don't clutter up your program with unnecessary detail until you need it. -###Exercises +### Exercises 10.1 Write a program which reads the names of a group of students and creates an array of pupil records, holding name, age, address and marks in maths, English and physics. Allow student details to be filled in in any order, copying the details into the correct entry in the array. Print out the contents in the order in which the list of names was first given. 10.2 Extend 10.1 to sort the names into alphabetical order as it first reads them and to print the records in this order. 10.3 Further extend your program to calculate each student's average mark and to print separate lists ordered alphabetically, by order of marks in each subject and by overall average mark. -###Rearranging lists +### Rearranging lists An array is an ordered list. Each item in the list is numbered and can be accessed by this number combined with the name of the array. This is very useful where the order is fixed or is irrelevant. Exercise 10.2 shows that it is often useful to be able to rearrange the order in which the items of a list are held. Exercise 10.3 takes this further and shows that the same items may need to be thought as being on several different lists, held in different orders. The array can only do this by clumsy rearrangement of its elements or by copying the same elements into a number of different arrays. @@ -299,7 +299,7 @@ Once the correct position in the list has been found it is necessary to move all Fortunately, SIMULA allows us to create much more flexible lists, tailored to the needs of a program. These use the ability of class objects to contain pointers or links, in the form of reference variables, to other objects. Lists can be formed in this way, known as "linked lists". -###Reading into a linked list +### Reading into a linked list Diagram 10.1 shows how a new object is added to a linked list. Each object of class Linked\_Lab contains an attribute called Next, which is of type ref(Linked\_Lab). The corresponding program is shown in example 10.7. New objects are added to the end of this list. Pointers to the current first and last members of the list are held in the ref(Linked\_Lab) variables List\_Head and List\_End. @@ -405,24 +405,24 @@ Example 10.7: Building the linked list in Diagram 10.1. end..of..printing..list end**of**program -###Class reference comparison +### Class reference comparison The final while loop of example 10.7 contained a class object reference comparison. This used the operator =/=, which means "does not reference" or "does not point at". Formally, it tests for reference inequality. It is similar to the text reference comparator. There is also a positive equivalent, ==, meaning "does reference", which tests for reference equality. Thus if P1==P2 then OutInt(3,3) would print 3 if the class object reference variables P1 and P2 pointed to the same object. -###None +### None The same comparison also used None as one of the reference variables. None is a reference to no object. Any reference variable initially references None. Any reference variable can be pointed back to None. Reference variables of any type can be pointed at None. It is the initial value of reference variables, regardless of their type. -###Exercises +### Exercises 10.4 Extend example 10.7 to build a list of five objects. 10.5 Write a program to add items to the start of a linked list, rather than the end, and which builds a list of four such items. -###Generalising simple linked lists +### Generalising simple linked lists In exercises 10.4 and 10.5 you will have noticed that for all items except the first, adding a new item to a linked list requires the same sequence of statements. There is a clear case for using procedures for such tasks. If we think further, a linked list is a data structure with attributes unique to itself. Each list has a head and a tail (although it is possible to use just a head). Furthermore, our proposed procedures for adding items at the beginning and end of a list operate only on attributes of a list object. It is sensible to define a class embodying these attributes for use in processing linked lists. Example 10.8 shows how this might be implemented. @@ -497,21 +497,21 @@ Example 10.8: Class Label_List. end; OutImage end**of**program -###Exercises +### Exercises 10.6 Write a program which locates and removes an item in a linked list. 10.7 Add local procedures to class Linked_Lab, one of which inserts a label object after a given member of the list and one of which removes a label from the list. 10.8 Rewrite your answers to 10.2 and 10.3 using linked lists instead of arrays. Remember that an object can have as many ref attributes as you like and so can be on as many linked lists simultaneously as you wish. -###Arrays versus linked lists +### Arrays versus linked lists We have seen that arrays are a very convenient way of storing simple values and references to more complex class objects in an ordered list. We have seen that rearranging such lists is very inconvenient. Although the use of dynamic bounds allows greater flexibility, the need to specify the overall size and bounds of an array at the start of the block in which it is declared still imposes quite strict limits to the usefulness of arrays. Linked lists are much easier to rearrange and to extend. We do not need to fix an upper limit to the number of elements in them. The same object can exist on several such lists at once. On the other hand, if we wish to find item number six, say, on a linked list, we must chain through, counting as we go. In an array accessing item number six is trivial. There are strengths and weaknesses in both these list structures. It is a question of picking the more appropriate one for your purposes. As we shall see later, linked lists can be even more flexible than those we have used so far and some of their limitations can be reduced. For certain very common purposes, however, arrays remain the best choice. -###Summary +### Summary We have seen how simple, ordered lists can be held in arrays. The means for declaring and accessing arrays have been learned, especially how to use subscripted variables to treat any item of an array as a simple variable of the same type. The use of dynamic bounds to allow variable sized arrays has been shown diff --git a/en/Chapter11/README.md b/en/Chapter11/README.md index 10f71c6..d2d3db5 100644 --- a/en/Chapter11/README.md +++ b/en/Chapter11/README.md @@ -1,8 +1,8 @@ -#CHAPTER 11 - Like parent like child +# CHAPTER 11 - Like parent like child -##Sub-classes and complex Boolean expressions +## Sub-classes and complex Boolean expressions -###Building on what you have +### Building on what you have One of the important ways we have of making sense of the world is to classify things. We put them into categories or classes. SIMULA allows us to reflect this very natural way of thinking in the way we write programs. When classifying things we first group them either very generally, e.g. as animal, vegetable or mineral, or very specifically, e.g. as bees or roses, depending on circumstances. These approaches correspond to the programming techniques known as "top down" and "bottom up" design, respectively. @@ -29,7 +29,7 @@ Diagram 11.1 - Family tree of class File | Outfile class PrintFile The syntax of a sub-class declaration is very simple. The keyword class is preceded by the name of the parent class. Otherwise the declaration is the same as for a simple class. The new class is said to be "prefixed" by the parent. -###A word processing example +### A word processing example We can consider a chapter in a book as a sequence of pages. This sequence can, as we have seen, be represented as an array or as a linked list. In either case we want all the pages to be of the same type. If they are not, they cannot be held together. All items in an array must be of the same type. All items in a linked list are joined by pointers declared as ref(type) variables, with type the same for all. Thus we need a basic class Page. Each Page will contain printed blocks. The first Page in each Chapter will have a title block, followed by a sequence of other blocks. The other blocks could contain text or diagrams. A linked list of Print_Block objects can represent the contents of a Page. @@ -102,14 +102,14 @@ Example 11.1: Representing pages as Print_Block objects. new Page; end This parent class is used to prefix the three classes representing different types of block on a page. Each contains additional attributes, actions or both. Two contain parameters. Note that these also are additional to those in the parent class. -###A few properties of sub-classes +### A few properties of sub-classes The program shows some important features of sub-classes. The attributes of the prefixing class are normally visible in its sub-classes. As we shall see later there is a way of "hiding" the parent's attributes. Note that this visibility of local quantities is unlike any other type of block, such as a sub-block or procedure body. The parameters of the prefixing class must still be given when generating a new object of one of its sub-classes. Thus, the generation of a new Title\_Block requires three parameters, the two declared for parent Print\_Block followed by the additional one for Title_Block. The prefixing class parameters always come before the sub-class parameters. The actions specified for the prefixing class are performed, before those of the sub-class, when a new sub-class object is generated. Thus the for-loop which sets the elements of Contents to blank filled texts of the desired Width, takes place before any of the actions of Title\_Block, Text_Block or Diagram. A reference variable which points to objects of the prefixing class can also point to objects of its sub-classes. Variables which are declared as ref to a sub-class cannot point to a parent object, however. Thus the use of ref(Print\_Block) variables for all the links in the list of blocks means that objects of type Print\_Block, Title\_Block, Text\_Block and Diagram can all fit onto the same list. They are all "qualified" by the type Print\_Block. On the other hand, objects created by the generator new Print_Block, would not be allowed on a list linked by pointers declared as ref(Text\_Block). -###What the program does +### What the program does The program reads text from SysIn. This text is assumed to end with a line starting with the characters "$E", meaning end of page. The character '$' followed by a sequence of letters and numbers is assumed to be a directive, telling the program what the next sequence represents. Lines of 80 characters are assumed. The directive "$B" means that a Title\_Block is required. The number of, mostly blank, lines to be used, is given as an integer following the $B directive. The text for the title parameter is on the following line. The title is copied into the middle line of the block by the actions of a new Title_Block. @@ -118,7 +118,7 @@ The directive "$C" means that a new Text\_Block is required. The number of eight The directive "$D" means that a space for a diagram should be left. Again the number of lines to be left follows and the next line is the text to be used for the title of the diagram. This is copied into the first text elememt of Contents by the actions of a new Diagram object. -###Exercises +### Exercises 11.1 Add a printing procedure to class Print_Block and use the program to process a source in the required format. 11.2 By using a linked list to hold lines, remove the need to specify the number of lines in a Text_Block. Use a line breaker to avoid splitting words at the ends of a line. @@ -164,7 +164,7 @@ Example 11.2: Concatenation .. sub-sub-classes new InnerMost("One","Two","Three") end**of**program -###Sub-sub-classes +### Sub-sub-classes As is clear from the File family tree, a sub-class can prefix its own extensions. The rules given above still apply, except that the parameters, local variables and actions of all three classes are combined in the grandchild, in the order grandparent, parent, grandchild. Example 11.2 shows this in a trivial example. Try compiling and running it to see the effects for yourself. @@ -175,7 +175,7 @@ The sequence class, sub-class, sub-sub-class etc. is called a "prefix chain". In more technical descriptions the first class on the prefix chain is called the "outermost" and the final one the "innermost". A sub-class is "inner" to its parent, grandparent etc. A class is "outer" to its sub-classes, their sub-classes etc. -###Name conflicts in sub-classes +### Name conflicts in sub-classes It is quite legal to declare identifiers in a sub-class with the same name as those declared in its parent or another outer class. This is shown in example 11.3. The effects are simple to describe, but can sometimes be confusing to grasp. It is perhaps worth running 11.3 before reading on, to give you a practical experience of the concepts. In a parent class the use of the identifier always refers to the declaration of that identifier inside that class. @@ -248,7 +248,7 @@ Example 11.4: The use of inner. new Parent; new Child end**of**program -###Top and tailing - the use of inner +### Top and tailing - the use of inner The use of actions within classes should be familiar by now. The ability to build on these in suitably different ways in sub-classes is used in the three sub-classes of Print_Block in example 11.1. This is a very powerful feature of SIMULA. The usefulness of sub-class actions is increased still further by the inner statement. This allows a parent class to specify one set of actions to be performed before those of its sub-classes and another to be performed after them. Consider example 11.4. @@ -265,7 +265,7 @@ Only one inner statement can appear in a class body, since it can only have one A sub-class may contain an inner statement, in which the actions of any sub-sub-classes will be performed when it is reached, and so on along the prefix chain. Practical uses of this feature, especially in conjunction with prefixed blocks, will be demonstrated later in this book. -###Exercises +### Exercises 11.3 Use an inner statement in class Print_Block to write the number of lines created for that block when processing of it is complete. Write it to a different file from the one used for the actual text. 11.4 Study the following program. What would its output be? Try running it to check your answer. @@ -311,7 +311,7 @@ A sub-class may contain an inner statement, in which the actions of any sub-sub- new Centre; new Inner end**of**program -###The types of class objects +### The types of class objects We have seen in example 11.1 some of the rules governing the types or qualifications of class objects. Here we will consider these further and more systematically. We shall also see how to check the qualification of a class object. When a class object is generated it posesses all the attributes of the class whose name is given in the object generator. This includes any visible attributes from classes on its prefix chain, following the rules given above concerning name clashes. @@ -326,7 +326,7 @@ It is only legal to treat an object which is being remotely accessed as if it wa would be illegal. Breaking any of these rules will cause the SIMULA system to report an error, either during compilation or at runtime. Some extra features of SIMULA can be used to circumvent these restrictions, as we shall see later, but these checks provide an important safeguard against serious errors which could occur otherwise. -###Checking the qualification of an object +### Checking the qualification of an object In addition to checking whether or not two reference variables point to the same object (reference equality and inequality), SIMULA also allows us to check the qualification of any referenced object. To do this we use the reference comparators is and in. The operator is checks whether an object is qualified by a particular class. It will only give the value True when the object's innermost class matches that with which it is compared. Thus @@ -371,24 +371,24 @@ Example 11.5: Use of is and in. OutImage end end**of**program -###Exercise +### Exercise 11.6 Rewrite the text processing program so that it recognises the directive $A. This is followed by a text sequence which is to be printed after all the other blocks. In every other way it is treated as a Text_Block. Use is to test the blocks and print them in the correct order. -###Some extra features for Boolean expressions +### Some extra features for Boolean expressions As we have often seen, comparisons are what make it possible to write most of our useful programs. You will probably have begun to realise that making the right test in the right place is vital to success in programming. To help with this, SIMULA provides facilities for making more than one comparison in a single begin statement, while loop or whatever. These facilities allow us to write neater, more compact code. At the same time they make it even more important to check when we use them that the right tests are being applied. A comparison is more formally called a "simple Boolean expression", giving the value True or False. The keywords True and False are themselves simple Boolean expressions, with a constant value. Boolean variables and Boolean procedures, like LastItem in a text, are also simple Boolean expressions. Thus a Boolean expression is a sequence of SIMULA which can be evaluated to True or False. -###not +### not The simplest extension to a simple Boolean expression is the Boolean operator not. The keyword not reverses the value of the Boolean expression which follows immediately after it. The Boolean expression 3 = 2 has the value False, and so the expression not 3 = 2 has the value true. -###and +### and When two Boolean expressions are linked by the operator and, the value of the combined Boolean expression is False unless both the linked expressions have the value True. The expression @@ -415,24 +415,24 @@ Examples 11.9: The use of imp. b) 4=4 imp 7=7; ! Value is True c) 2=2 imp 6=8; ! Value is False d) 10=2 imp 2<0; ! Value is True -###or +### or Two Boolean expressions linked by the operator or form a combined Boolean expression which has the value True if either of the sub-expressions has the value True. Only where both have the value False does the combined expression have the value False. It is easy to confuse the operator and with the operator or in ordinary speech, since we often use these words very loosely. You should take great care to get your meanings precise in SIMULA. The examples in 11.7 show the possible combinations. -###eqv +### eqv Two Boolean expressions linked by the operator eqv form a combined Boolean expression which has the value True if both sub-expressions have the same value and has the value False if the sub-expressions have different values. eqv is an abbreviation for "equivalent to". The examples in 11.8 show the possible combinations. -###imp +### imp imp is also used to link two Boolean expressions to form a combined expression. Its meaning is only of interest to formal mathematicians, but I include it for completeness. The possible combinations using it are given in examples 11.8. imp is an abbreviation for "implies". -###Summarising Boolean operators +### Summarising Boolean operators Table 11.1 show a summary of the effects of the various Boolean operators. B1 represents the first Boolean sub-expression, B2 the second. This sort of table is often called a "truth table". Table 11.1: Effects of Boolean operators. @@ -458,7 +458,7 @@ Boolean operators can be combined to form more complicated expressions. The rule 5. All imp operations are carried out. 6. All eqv operations are carried out. Example 11.10 shows this sequence for an unusually complicated sequence. -###Bracketing +### Bracketing Parentheses may be placed around any sub-expression. This has the effect of forcing the value of that sub-expression to be fully evaluated before the rest of the main expression and so can override the order given above. This is equivalent to the use of parentheses in arithmetic expressions. Example 11.11 shows the effects of bracketing on parts of 11.10. Note that the innermost brackets' contents are evaluated first and so on. @@ -482,7 +482,7 @@ Example 11.11: Evaluation of complex Boolean expression with bracketing. 4) False or True imp False 5) True imp False 6) False -###Hints on using Boolean operators +### Hints on using Boolean operators The use of and and or in particular can make programs shorter and easier to read. The sequence if I=J then @@ -499,7 +499,7 @@ and have exactly the same value, but the second is much clearer. Finally, a warning; do not try to be "clever" in your use of Boolean expressions. Keep them as straightforward and clear as possible. Sometimes it may be better to use two nested begin statements rather than a convoluted Boolean expression, keeping the program's meaning clear at the cost of making it slightly longer. -###Side effects and how to avoid them +### Side effects and how to avoid them I hope I am not over emphasising Boolean expressions. They are often the key to a successful program. They are certainly the cause of many errors in programs which may be very difficult to locate if we do not take great care to use them sensibly. Most of us will find and, or and not very useful and it is worth looking at one problem with the first two which is rare, but very hard to find when it does occur. In addition to or and and, SIMULA has operators or else and and then. These produce the same value as their simpler counterparts, as table 11.1 shows. They are included to allow programs to be written which run faster, at the expense of introducing the possibility of unpredictable side effects from procedure calls. In most cases and then is interchangeable with and, while or else is interchangeable with or. @@ -512,13 +512,13 @@ It is the second effect which can cause problems. If the calling of a type proce Example 11.12 shows a program with side effects. Running it and supplying first a sequence not containing 99 and then one which does contain it demonstrates the problem. It may seem "smart" to write like this. It is certainly an interesting technique. It is even more certainly a very unsafe one. -###Exercise +### Exercise 11.8 What are the values of the following expressions? 4=3 or 0>2 and 3=3 (4=3 or 0>2) and 3=3 4=3 or (0>2 and 3=3) -###Summary +### Summary This chapter has dealt with sub-classes, qualification and Boolean operators. We have seen how to use classes as prefixes to form families of sub-classes, which extend their parent's attributes. diff --git a/en/Chapter12/README.md b/en/Chapter12/README.md index 05e67cc..ae66814 100644 --- a/en/Chapter12/README.md +++ b/en/Chapter12/README.md @@ -1,13 +1,13 @@ -#CHAPTER 12 - A Language with Character +# CHAPTER 12 - A Language with Character -##Character handling, switches and jumps +## Character handling, switches and jumps -###Working with texts +### Working with texts Most of our examples have been concerned with some sort of manipulation of characters in the form of texts. Occasionally we have used GetChar and PutChar to manipulate the individual characters in them. At other times we have used Getint, PutFix etc. to manipulate groups of characters within texts. Any text processing or editing programs are heavily dependent on the manipulation of individual characters as well as their combinations. This chapter shows those features of SIMULA designed to help in this. Most of these features are system procedures. We start with two simple ones, shown in example 12.1. This shows a program which finds all the numbers in a text containing a mixture of digits and letters. It is assumed that no other characters will be present. -###Procedures Letter and Digit +### Procedures Letter and Digit SIMULA provides two Boolean procedures, Letter and Digit, both taking a single, character parameter. If this parameter is one of a-z or A-Z the procedure Letter will return the value True, otherwise it will return the value False. If its parameter is one of 0-9, Digit will return True, otherwise False. @@ -36,17 +36,17 @@ Example 12.1 : Sorting letters and numbers. OutText(NumbersOut); OutImage end -###Representing characters +### Representing characters Computers store characters in their memory as numbers. Each character is represented by a different integer value. Unfortunately there is no single system for this. The numbers representing each character can vary from machine to machine. In practice most machines use either the EBCDIC system or the International Standards Organisation (ISO) system. The ISO system is often called by its earlier name, ASCII. The two systems are shown in tables 12.1 and 12.2. These tables are known as the collating sequences for the two systems. -###Using the internal values +### Using the internal values It is sometimes useful to be able to find the internal number representing a character or to be able to convert a number into the corresponding character. SIMULA provides procedures for both of these. Example 12.2 shows a program which converts characters in a text which uses ISO characters into an equivalent text containing EBCDIC characters. This is often necessary when reading files transferred from another computer. -###Rank +### Rank System integer procedure Rank takes a single character value parameter and returns the number representing the character. In 12.2, the characters inside ISOText are in the ISO form and so the call @@ -112,14 +112,14 @@ Using the same example, if Rank (ISOText.GetChar) returns 32, having found a spa Thus the use of GetChar, Rank and indexing of the array EBCDICChar has found the value of the EBCDIC representation of an ISO character in our text. Now we need to convert this into a character. -###Char +### Char System character procedure Char takes a single integer value parameter, whose value must be legal as the internal representation of a character on that system. (This range should be specified in the documentation for the SIMULA system you are using). Char returns a character whose internal representation is the number passed as a parameter. It is important to note that Rank and Char do not concern themselves with which character set is being used, only with moving a number, held in some form such as a binary number, from a location reserved for a character to one reserved for an integer or vice versa. Char objects only if the integer is too large to fit into the, usually, smaller space used for a character. Interpreting characters according to ISO, EBCDIC or whatever is only done by some reading and writing procedures. Thus, in the example, the EBCDIC representation of the character obtained from ISOText, is passed to Char, which returns a character with this as its internal representation. This can then be written as the EBCDIC translation into EBCDICText, using PutChar. -###Avoiding character set problems +### Avoiding character set problems When writing character handling programs to run on any computer, it is very inconvenient to have to allow for the possible character sets on each particular machine. This makes it nearly impossible, in fact, to write truly portable programs using the procedures Char and Rank. Fortunately SIMULA has a way of avoiding this. On any but the oldest SIMULA systems, two more system procedures are supplied. They are called ISOChar and ISORank. They match Char and Rank exactly except that they work entirely in terms of the ISO character set. @@ -173,14 +173,14 @@ The program uses the technique, seen earlier, of creating two references to the Note that this program would not work for the EBCDIC character set, if Char and Rank replaced ISOChar and ISORank. This demonstrates the usefulness of the ISO procedures in writing portable programs rather neatly. -###Exercises +### Exercises 12.1 Because of hardware problems, a file has been corrupted. It now contains a number of unprintable characters. Assuming that letters, digits, spaces, full stops, commas, colons and semi-colons are the only characters which should be present, write a program which will remove the others. 12.2 Write a program which converts all upper case letters to lower and all lower to upper in a file. 12.3 Go back to exercise 7.8. Using this add the capability to your editor to change the case of the next letter from its current position. -###Making quick decisions +### Making quick decisions When writing our text formatting program in chapter eleven, we were forced to use more and more deeply nested if statements to check which directive was being read. This becomes rather clumsy and difficult to read when more than a few choices are possible. It is also slow to run when lots of checks must be made before a course of action is selected. The help with this sort of situation, SIMULA contains a feature called a switch. To see how this works, consider example 12.4. This is example 11.1 rewritten with a switch. @@ -258,17 +258,17 @@ Example 12.4 : The use of a switch new Page end.of.program The letters in the directives are in alphabetic sequence starting with 'B'. Thus they follow the ISO collating sequence. Thus, by subtracting ISORank ('A') from the ISORank of each directive's letter, we can obtain a value between one and three, inclusive. Each integer value so obtained represents one of the three directives. -###switch declarations +### switch declarations The switch declaration is unusual, in that it contains the value assignment operator, :=, as well as identifiers. The syntax of such a declaration is the keyword switch, followed by an identifier giving the name of the switch, followed by the value assignment operator, followed by a list of so called "designational expressions". Designational expressions can take a number of forms. In the example they all have the commonest form, a simple identifier. The identifiers used in such a list specify places in the program to which a "jump" may be made. If you look at the example, three identifiers are listed. (The minimum is one and the maximum will be different on different SIMULA systems.) Further on in the program, each of these identifiers occurs again, followed by a colon. This second occurence is called a label. -###Label declarations +### Label declarations An identifier followed by a colon is a declaration of a label for the following statement. Such a declaration is different from those of any other type, since it can occur in the middle of a sequence of statements, rather than before any statements. The example contains four label declarations. The first three, TitleB, TextB and DiagB are used to label the next statement. The fourth, Repeat, appears to label the keyword, end. end is not a statement and so to preserve the rule that label declarations always precede statements, there is said to be an imaginary statement between the colon and end. -###go to statements with switches +### go to statements with switches The switch, Action, is used in a statement starting with the keywords go to. In fact these can be written as a single keyword goto, if you prefer. This is the only combination of keywords where this is allowed. A go to statement is the keyword(s) go to followed by a designational expression. In the example the switch identifier, Action followed by an integer value in parentheses is used. This is the other form of designational expression that we shall use. This integer value is an index to the list of designational expressions in the switch declaration above. Thus it can be used to identify a label declaration and through this the next statement to be executed. @@ -293,29 +293,29 @@ In the example three statements have the form of go to followed by an identifier These three statements all cause the program to jump to the statement labelled by Repeat. This takes the program to the InImage at the end of the compound statement of the while loop. In other words, once the actions for that directive are complete, the program jumps to start processing the next line, which is assumed to contain the next directive. -###Exercises +### Exercises 12.4 By extending the list for the switch declaration, moving the position of Repeat and adding a new label declaration, rewrite example 12.4 without the while loop. 12.5 What would happen in example 12.4 if the go to Repeat statements were missing? Try removing them to check. Note the effect carefully. -###Notes and warnings +### Notes and warnings Some people write very intricate programs, which use lots of go to statements. In certain, rather limited, programming languages this is necessary. In SIMULA it is almost never needed. The use of too many go to statements makes programs very hard to read and understand. They should only be used when absolutely necessary or in the sort of situation shown in example 12.4, where a switch can simplify a program and make it easier to extend. It is important in a program using a switch to provide label declarations to match all the designational expressions in the switch declaration. It is not illegal to declare a switch which leads to non-existent labels. It is a runtime error to try to jump to one. In fact it is often best to check before the go to statement that the value of the expression used in the subscripted switch variable is not too large for the list in the declaration and to print an error message or warning if necessary. -###A very special jump +### A very special jump A rather new feature in SIMULA, which may not exist in some older systems, is the system procedure Terminate_Program. This causes a jump to the very end of the program, regardless of the current position. This can be useful in providing warnings of disastrous errors and then stopping the program. Terminate_Program is the only way for a program using a prefixing separately compiled class containing an @i(inner) statement (see chapter 16), to stop itself without executing the instructions following that @i(inner). It is the only way to stop a program dead from anywhere within it and guarantee that no further actions will be carried out. -###Switches and labels as parameters +### Switches and labels as parameters It is possible to pass switches and labels as parameters to procedures. The default mode is reference and name is also legal. Using such a parameter, or a switch or label from a block enclosing the one the program is currently in, it is possible to jump out of a block. The normal rules for ending the appropriate type of block will apply. -###Summary +### Summary We have looked at how characters are represented by numbers and seen the procedures which allow us to use this. We have seen the use of switches and labels, in go to statements and as parameters. diff --git a/en/Chapter13/README.md b/en/Chapter13/README.md index c34c1e1..7d0bf39 100644 --- a/en/Chapter13/README.md +++ b/en/Chapter13/README.md @@ -1,8 +1,8 @@ -#Chapter 13 - Let Us See what We Can See +# Chapter 13 - Let Us See what We Can See -##Inspection and Remote Accessing +## Inspection and Remote Accessing -###Recap +### Recap So far we have treated inspection and dot notation accessing as the same thing. In most simple cases they are. In other situations they may be used to do rather different things. In particular the inspect statement can be used for much more than just a convenient shorthand. Essentially we have seen that the dot notation form of remote accessing allows us to use the attributes of a class object from outside it. It is also used to access the attributes of text objects, which are not class objects. @@ -57,7 +57,7 @@ b) inspect statement. for Int := Int step 2 until 6 do Txt := "Txt" end end -###Limitations of dot notation +### Limitations of dot notation The most important limitation on dot notation occurs with an object qualified by a class which itself has classes declared within its body or within the body of a prefixing class. This is shown in example 13.2a. Class Outside contains a class declaration for Inside and other attributes. The main program contains a variable Outsider which references an object of class Outside. Using dot notation we cannot access any of the attributes of Outsider from the main program block. @@ -142,7 +142,7 @@ Another problem with remote accessing is that it is clearly nonsense to use a re To get around these problems we can use extensions of the inspect statement. -###inspect plus otherwise +### inspect plus otherwise The simplest extension allows us to detect the use of references which currently do not point to a class object. Such references are said to point to an imaginary object, with no attributes, called None. This is the only object that any reference, regardless of its type, can point at. Consider examples 13.3. The first program would simply ignore some elements of the array References, since not all the reference variables in this array have been pointed at objects of class Example. The second program, on the other hand, will detect such variables and report which they are. It does this by adding an otherwise clause to its inspect statement. @@ -244,7 +244,7 @@ c) The same program without inspect. end**of**for**loop end++of++program -###The use of inspect plus when +### The use of inspect plus when The inspect statement used so far allows us to treat None and one particular type of class object differently. By adding a feature called the when clause, we can treat a class object according to its actual type, out of a range of possible alternatives. Example 13.4 shows the use of an inspect statement with when clauses to process a linked list. All the objects on the list belong to classes sharing a common prefix. They are linked by variables declared as ref to this common prefix. @@ -318,7 +318,7 @@ Example 13.4: Mixed list processing using when. end--of--while--loop end++of++program -###A practical example - simple sorting and merging +### A practical example - simple sorting and merging Example 13.5 shows the use of a when clause to help in processing records which are read in unsorted. The records are of four types and are marked by the contents of their first line. The first character of this line is 'M' for a male and 'F' for a female. The second character is 'A' for an accountant and 'D' for a dancer. Input is terminated by a line containing ".end" as its start. @@ -449,7 +449,7 @@ Example 13.5: Merging and sorting using inspect. if Accountants=/=None then Write_List("Accountants",Accountants) end++of++program -###Exercise +### Exercise 13.1 A theatrical agent has a file of records of different kinds of artists. He also has a file of records of requests for artists to be sent for audition. Assume that there are artists who are actors, musicians, singers and comedians and that requests may be for any of these. Further, assume that requests may specify the sex of the required artist and the age, with the age given as child, youth, mature or elderly. Write a program, based on the techniques used in example 13.5, to match requests and artists and print lists of all suitable artists for each request and all suitable requests for each artist. Getting round the qualification rules @@ -499,12 +499,12 @@ Example 13.6: Uses of qua. ! c); ARef2 qua B.I :- Copy("No inside to get to") end++of++program -###Syntax and semantics of reference expressions using qua +### Syntax and semantics of reference expressions using qua The use of qua is in expressions giving a reference to a class object. Its syntax is any reference to a class object, followed by the keyword qua, followed by the name of a class. This group is still a reference to the class object, but it is accessed at the prefix level defined by the class specified. Only the attributes of this class and any prefixes to it may be accessed. -###Referencing yourself +### Referencing yourself This chapter has introduced some very powerful concepts, but the usefulness of them is not always immediately apparent. It is only when you have to write quite complex programs that you may appreciate qua, for instance. One very useful but much simpler feature in SIMULA is the ability of an object to reference itself. It is achieved by using the keyword this. Example 13.7 shows the use of this. @@ -641,22 +641,22 @@ Example 13.7: Using this in 13.5. if Accountants=/=None then Write_List("Accountants",Accountants) end++of++program -###this in inspect statements +### this in inspect statements It is important to remember that the statement following the keyword do in a simple inspect and the statements in the when clauses of the extended inspect are treated as if they were inside the body of the object inspected. It is therefore possible to use this in these statements to refer to the inspected object. -###Reference parameters +### Reference parameters We have used references to objects as parameters without really considering the implications. We shall do so briefly here. References to class objects may be declared and passed as parameters to both procedures and classes. They are passed to both by reference as a default. They may be passed by name to procedures but not to classes. They may never be passed by value. (See tables 6.1 and 9.1.) The actual reference passed when the procedure is called or the class object is generated, must be compatible with the class specified in the declaration. This means that its qualification must be equal or inner to the declared class, just as in a reference assignment. -###Exercises +### Exercises 13.2 Rewrite example 13.7. Add a procedure Into to class linker. This takes one parameter which is a ref(Header). When Into is called it should insert the Linker object into the list of the Header passed. What mode should be used for the parameter? 13.3 Extend Into in 13.2, giving it a second parameter which is a ref to Linker. When called it should now insert the object through which it is accessed into the list after the object referenced by its second parameter. Beware of None. What modes should be used here? -###Summary +### Summary We have examined the uses, advantages and limitations of the dot notation for remote accessing. We have seen the full use of the inspect statement in both its simple and extended forms. diff --git a/en/Chapter2/README.md b/en/Chapter2/README.md index b78e1d6..6faa88f 100644 --- a/en/Chapter2/README.md +++ b/en/Chapter2/README.md @@ -1,10 +1,10 @@ -#Chapter 2 +# Chapter 2 -#\- and end at the end +# \- and end at the end -##The nature of correct programs +## The nature of correct programs -###Rules and penalties +### Rules and penalties Chapter one gave an example of a correct program. When you altered it as you were asked to in exercise 1.3 and recompiled it, some of the results will have been incorrect programs. (If you have not yet completed the exercises in chapter 1, you should do so now. It will be much easier for you to follow this chapter.) The compiler will have printed error messages for some of these variations. It may also have printed warnings. Sometimes, though probably not in any of your attempts at 1.3, the compiler will report success in producing the machine instruction version, but the part of the SIMULA system which runs the program, which we call the runtime system, will print an error message or warning during the execution of the program. @@ -17,12 +17,12 @@ Even when a program compiles and runs without producing error messages, the prog When it comes to writing correct SIMULA programs, there are two sets of rules. Although it is not always sensible to separate them, the error messages from the compiler may refer to mistakes in this way and so we will look at them briefly now. -###Syntax rules +### Syntax rules The commonest errors reported by a compiler are those which do not obey the grammar or "syntax" of the language. Often they are the result of typing errors. If you still have not managed exercise 1.1, this is probably because of a syntax error caused by mistyping. The rule that a program block must start with begin and finish with end is a syntax rule. -###Syntax of declarations +### Syntax of declarations The declarations @@ -43,7 +43,7 @@ As we shall see later, this sequence could still be correct SIMULA, meaning the Before considering this second category, let us look at some more syntax rules. These still deal with our earlier examples and will probably answer some questions which have occurred to you already. -###Syntax of identifiers +### Syntax of identifiers We have used the word identifier as the technical term for the name given to something in our programs. So far we have not considered what an identifier must look like. The identifiers which we have used so far are @@ -71,7 +71,7 @@ The following are valid identifiers MAX_SIZE G43 I -###Syntax of blocks +### Syntax of blocks We have already looked at the syntax of blocks informally, now let us be a little more formal. The rules for a block are as follow. A block starts with the keyword begin, which, like all keywords, must have at least one space following it or be the last word on a line. @@ -93,17 +93,17 @@ The following are valid blocks end Example 2.3 - begin - integer I; - real Arc; - I := 5; - Arc := 3.2; - OutInt(I,3); - OutImage + begin + integer I; + real Arc; + I := 5; + Arc := 3.2; + OutInt(I,3); + OutImage end Although all these blocks are syntactically correct, 2.1 will not result in any actions, since it contains no statements. 2.2 will cause an error to be reported, since there is no declaration to set aside space and define a type for Result before it is used in the statement. -###Exercises +### Exercises You are probably getting rather impatient with all these rules. Let us try out a few of them. In each of the following program blocks, find and correct the syntax errors. @@ -141,9 +141,9 @@ We have already defined identifiers. We shall define constants properly in the n Examples 2.4: Procedure calls. - OutImage No parameters. Moves output to next line. - Outtext("HI") One parameter, a text, which is printed on the current line. In this example a text constant is used as the parameter. - OutInt(643,3) Two parameters, both integers, separated by a comma. Prints out the first integer on the current line, padding on the left with spaces if this produces fewer figures than the second integer. Either or both the integer constants given as parameters in the example could have been replaced with identifiers or expressions. + OutImage No parameters. Moves output to next line. + Outtext("HI") One parameter, a text, which is printed on the current line. In this example a text constant is used as the parameter. + OutInt(643,3) Two parameters, both integers, separated by a comma. Prints out the first integer on the current line, padding on the left with spaces if this produces fewer figures than the second integer. Either or both the integer constants given as parameters in the example could have been replaced with identifiers or expressions. Assignment statements have an identifier followed by optional spaces, followed by the assignment "operator", followed by optional spaces, followed by an expression. The assignment operator is the sequence colon followed by equal-sign, :=. Before giving an informal description of expressions, it is probably best to consider the examples of assignment statements given as 2.5. @@ -160,7 +160,7 @@ Examples 2.5: Assignment statements. Next := Average*Number + 2 The use of spaces before and after the assignment operator has no effect on the correctness of the statement. This applies to all "operators" in SIMULA. -###Expressions +### Expressions Several kinds of expressions are shown to the right of the assignment operator in these examples. The simplest of these is a constant, such as 3 or "PLEASE TYPE YOUR NAME". These are explained more fully in the next chapter. An expression can also be a single identifier, such as Last in the second example. @@ -173,7 +173,7 @@ is the identifier Last followed by the addition operator followed by the constan Average*Number + 2 is the identifier Average followed by the multiplication operator followed by the identifier Number followed by the addition operator followed by the constant 2. We shall not attempt a complete definition of expressions, but explain them as we need to use them. These examples should give a feel of what is meant. -###A note on operators +### A note on operators The commonest arithmetic operators are given below. For a complete outline of mathematical operators, see appendix A. @@ -183,7 +183,7 @@ The commonest arithmetic operators are given below. For a complete outline of ma / Division with non-whole numbers (reals) // Division with whole numbers (integers) := Assignment -###Saying what you mean +### Saying what you mean As we looked at the rules for writing parts of SIMULA programs, we found that it was possible to write SIMULA whose syntax was correct but which was still illegal. There are extra rules to be obeyed. These spell out the meaning of a sequence of SIMULA. When the way we write the parts of such a sequence is correct, it is still possible that we have put these parts together in a way which has an illegal meaning. These rules of meaning are sometimes called the semantic rules or, more simply,semantics of the language. English has syntax and semantics in the same way, although they are far more complex than those for SIMULA. Let us look at an example in English of a sentence whose syntax (or grammar) is correct, but whose semantics (or meaning) is nonsense. @@ -212,24 +212,24 @@ This time we have not defined T1 as having a type which fails to match "3". T1 h So, a few rules about how we must write SIMULA to avoid semantic errors. -###Semantics of declarations +### Semantics of declarations **The same identifier cannot be declared twice in a block.** The identifier is used to name a space in the computer's memory which is large enough to hold a value of the type specified. Whenever the identifier is used subsequently, it refers to this space and this type of value. -###Semantics of procedure calls +### Semantics of procedure calls **A procedure call must have the correct number of parameters.** Each parameter must be of the correct type. This is explained in more detail in the next chapter. The actions of the procedure are performed, using the parameters to provide information for the procedure if necessary. -###Semantics of assignments +### Semantics of assignments **The type of the expression to the right of the assignment operator must be "compatible" with the type of the identifier on the left.** The value of the expression on the right will be stored in the location reserved for the identifier on the left. -###Semantics of expressions +### Semantics of expressions **The types of the quantities in an expression must be compatible. The type associated with the value of an expression is determined by the types of the quantities in it, except when the division operators are used. In this case the type is the same as the operator, i.e. integer for "//" and real for "/".** The working out of an expression by the SIMULA system, known as its "evaluation", is done in the following order: @@ -240,12 +240,12 @@ Working from left to right all additions and subtractions are performed. This is explained more fully in {{ book.AppendixA }}. -###Semantics of blocks +### Semantics of blocks Any identifier used in a statement in a block must already have been declared. The statements in the block are performed in the order indicated. -###Syntax and semantics of a comment +### Syntax and semantics of a comment **A comment is a special sequence in SIMULA which is treated as a space by the compiler. It contains a message which explains what is going on around it in human terms. Its syntax is quite simple.** A comment is: @@ -290,7 +290,7 @@ Example 2.6: The use of comments. OutText(T); OutImage end Double space remover -###Summary +### Summary This has been a longer chapter and has introduced a lot of important ideas. You should not worry if you do not see the point of some of it yet. Whenever we come to look at a new feature in SIMULA you will see how the concepts of syntax and semantics help define the ways in which the feature can be used. Within a few chapters you will find that you are using words like syntax without noticing. In the meantime, you may need to refer to this chapter while reading some of the following chapters, until you feel confident. We have looked in this chapter at the rules that tell you how you must write your program for the compiler to be able to make sense of it. These are called the "syntax" of SIMULA. @@ -303,7 +303,7 @@ We have seen the important semantic rules for those parts of SIMULA whose syntax We have looked at the rules for comments, which have no meaning, only syntax. -###Exercises +### Exercises Correct the errors in the following program blocks. 1. begin diff --git a/en/Chapter3/README.md b/en/Chapter3/README.md index f162d9e..c874491 100644 --- a/en/Chapter3/README.md +++ b/en/Chapter3/README.md @@ -1,11 +1,11 @@ -#Chapter 3 +# Chapter 3 -##Type Cast Actors +## Type Cast Actors -###The importance of types +### The importance of types So far we have seen three types: integer, real and text. The only one we have looked at in any detail is integer. In fact SIMULA contains several other types as keywords or combinations of keywords. In addition it is possible for you to create combinations of these simple types and give them names, by using the class mechanism. In this chapter we will look at the simple types which are already defined in SIMULA. -###Types in assignments +### Types in assignments A type is given in a declaration so that the SIMULA system knows how much space to allow for the declared quantity. The system checks whenever a new value is stored into this location that the value is of the same type. If the types are different then the system may do one of two things. @@ -40,7 +40,7 @@ Clearly we must be very careful how we use types. Even where we are allowed to m Allowing the system to convert things in this way is sometimes known as "implicit conversion". SIMULA also provides procedures which can be used to carry out type conversion in a controlled way. In general it is safer to use these "explicit conversion" procedures, so that it is obvious when reading the program what is happening. We shall look at the rules used in implicit conversion at the end of this chapter. -###Types in expressions +### Types in expressions The rules about mixing types in assignments also apply in expressions. For instance, we are not allowed to add together an integer and a text. Example 3.3: A legal mixing of types in an expression. @@ -77,13 +77,13 @@ Where the integer division operator, //, is used in an expression, the values mu This subject is covered in more detail in the mathematical {{ book.AppendixB }}. -###Types of parameters +### Types of parameters Exactly the same rules apply where values are passed as parameters as apply when they are assigned. In effect the parameter given is assigned to a location with the type specified for that parameter. This will be discussed further in {{ book.Chapter5 }}. -###Standard types +### Standard types We shall now look at each of the simple types provided in SIMULA. For those who wish to use SIMULA for mathematical programming, {{ book.AppendixB }} contains more information on the use of arithmetic types. -###integer +### integer As we have seen, values are of type integer if they are whole numbers. They may be positive, negative or zero. On any particular SIMULA system there will be a largest positive and a smallest negative number which can be held in an integer location. The documentation for a particular system will tell you what these limits are. There are system constants which contain them and these may be used in your programs to check that your values do not exceed them. They are called MaxInt and MinInt respectively and are described in {{ book.Chapter20 }}. Such limits do not normally cause problems. @@ -99,7 +99,7 @@ Example 3.3: integer constants Spaces after the plus or minus are ignored. Spaces between digits are not allowed. It is also possible to give integer constants in other number bases. This is described in mathematical {{ book.AppendixC }}. -###real +### real A real value is a number which is not necessarily whole. It is held in a form which allows it to contain a fractional part. In common speech it is what is known as a 'decimal' number or decimal fraction, i.e. it is written with a decimal point separating the whole and fractional parts of the number. A real value is restricted both by a largest/lowest range and by the number of significant decimal places which can be held. Again this will be explained in detail in the documentation for your SIMULA system. There are two system real constants, Maxreal and MInReal, which may be used to check them in your programs. These are described in {{ book.Chapter20 }}. Again they will not cause problems for most users. @@ -116,7 +116,7 @@ Example 3.4: Legal fixed point real constants. The use of spaces is not allowed between digits or between a digit and the decimal point. Mathematicians often use another notation to write decimal values, especially where these are very large or very small. This way of writing them is known as "floating point" and is also allowed for writing real constants in SIMULA. It is described in mathematical {{ book.AppendixB }}, since most programmers will never use it. -###character +### character A character holds a value which represents a single character. SIMULA allows you to use any of the characters in the "character set" of the computer that you are using plus the characters defined by the International Standards Organisation (ISO) character set standard. (This is sometimes known as the ASCII character set.) More details on character sets are given in {{ book.Chapter12 }}. It is important to stress that a character has a different type from a text (see below). @@ -141,7 +141,7 @@ Example 3.5: Legal character constants Note that case, i.e. the difference between capital and small letters, is significant in character constants. Thus 'A' and 'a' are not equivalent. Note also how a single quote is represented as a character constant. -###Boolean +### Boolean A Boolean quantity can only have two values. These are True and False. The use of Boolean quantities may not be intuitively obvious and we merely mention them here. They will be considered in more detail when we look at conditional statements and loops. @@ -150,7 +150,7 @@ A Boolean can be assigned the value of any conditional expression and can be use Boolean constants can only be represented by the keywords True and False. -###text +### text A text variable is used to refer to and manipulate sequences of characters. A sequence of characters is often known as a "string". In the examples using text variables so far we have often assigned strings as the values to be placed in locations declared as type text. From this it might seem that a text and a string are the same thing. In fact a text is more complex than a string and we shall spend most of chapters 5 and 8 looking at what a text really holds. Text constants are strings, i.e. sequences of characters, surrounded by double quotes. Each character in a string can be any of those in the ASCII (ISO) standard set. @@ -176,7 +176,7 @@ Example 3.6: Legal text constants. Note that the last string shown in 3.6 will contain only one double quote. When you want to have a text constant which contains one double quote you must type two, so that the compiler knows that it is not the end of the string. Another example showing this is: "This string contains only one "", but we must type two." Note also that the single character text constants "%" and """" are not the same as the character constants '%' and '"'. They have different types. -###Initial values +### Initial values An identifier of a certain type, which is not declared as a constant (see later in this chapter), is often referred to as a "variable" of that type, since, unlike a constant of the same type, its value can be changed by assigning to it. When we declare such variable, the SIMULA system places an initial value in the location identified. This value is the same on all SIMULA systems on all computers for all variables of a given type. Thus it is quite legal, and meaningful, in SIMULA to write @@ -198,7 +198,7 @@ The values placed in each type of location are given below. text NoText, the empty text, referring to an empty string. Equivalent to "". -###Implicit conversion of reals and integers +### Implicit conversion of reals and integers When a real value is assigned to an integer location or vice versa we have said that the value will be converted to one with the type of the location. When integers are converted to reals, no problems are involved in understanding what will happen. The values 3 and 3.0 are usually thought of as identical and such a conversion presents no ambiguities. On the other hand, when reals are converted to integers, the result depends on how we deal with the fractional part of the real value. How do we get get rid of the figures to the right of the decimal point? @@ -233,7 +233,7 @@ Since no armchair programmers are allowed you should now try compiling and runni There is more on this subject in mathematical {{ book.AppendixB }}. -###Constant declarations +### Constant declarations Constant declarations were introduced into SIMULA very late on and are still regarded as controversial by older Simula programmers. They should be used with some restraint if you want to move your programs to other systems. Older SIMULA systems will not have constant declarations. A constant declaration allows an identifier to be assigned a value in its declaration. This identifier may not then be assigned another value. This can be very useful when using the same value frequently in a program, especially when the value is easily mistyped or has no obvious meaning. @@ -260,7 +260,7 @@ Example 3.8: Constant declaration. OutFix(2*Pi*Radius,6,12); ! 2 times Pi times Radius; OutImage end..of..program -###Summary +### Summary We have looked in some detail at the importance of the type associated with a value. In particular, we have noted that values can only be stored in locations of the same type. Attempts to store them in locations of a different type will result in implicit conversion to the type of the location or an error being reported. We have seen that mixing of types in an expression is restricted in a similar way. So is the use of types of parameters. @@ -275,7 +275,7 @@ We have seen how constant identifiers may be declared. {{ book.Chapter4 }} -###Exercises +### Exercises Correct the following programs. 1. begin diff --git a/en/Chapter4/README.md b/en/Chapter4/README.md index ea5131b..332b8de 100644 --- a/en/Chapter4/README.md +++ b/en/Chapter4/README.md @@ -1,8 +1,8 @@ -#CHAPTER 4 - if only +# CHAPTER 4 - if only -##Conditional statements +## Conditional statements -###What do computers do? +### What do computers do? It may seem a little late in this book to ask such a question, but we have really taken for granted what computers are and what they can do. if we are to use them as fully as possible, we need to understand exactly what they are capable of. Most people probably used to think of computers as giant, superfast calculating machines. More recently the idea of very small micro-computers has changed that Image somewhat. More importantly, the use of computers in word processing and graphics (particularly computer games) has introduced many more people to the use of computers in information processing and decision making. @@ -13,14 +13,14 @@ As programmers we can consider computers as performing three sets of functions, 2. Arithmetic calculations - we have seen some examples of this already. 3. Comparison of information and choice of actions depending on the result - this chapter will look at the basic mechanisms for this. -###Conditions and choices +### Conditions and choices The ability that makes computers more than calculators or fancy typewriters is the ability to perform different actions according to some condition or conditions, which it can determine to be either true or false. Computers can be told, "Check this condition. If it is true then do the following, otherwise do this other thing". In some cases the other thing is nothing. Put crudely, computers can make choices. What they cannot do, or, at least, as far as the author is aware, not yet, is decide which condition to test, or whether the actions which follow are really sensible. They must be told these things and programming languages have mechanisms for doing so. In SIMULA, the most important construction for making choices is the "conditional statement" or, as it is often known, the if statement. -###What is an if statement? +### What is an if statement? Example 4.1: Simple use of an if statement. begin @@ -41,7 +41,7 @@ The program checks the condition. If it is true, the statement is executed (or c An if statement may be used wherever a simple statement may be used. -###The if-then-else statement +### The if-then-else statement Consider example 4.2 which uses if statements. Example 4.2: Un-combined if statements. @@ -66,12 +66,12 @@ Example 4.3: The if-then-else statement. else OutText("NO"); OutImage end -###A "real" program +### A "real" program So far we have used only trivial examples to demonstrate features of SIMULA. None of them has had a purpose apart from that. Although writing and correcting such programs is interesting for a while, it soon becomes boring. We are now going to begin to construct a series of programs which have a very real and very practical purpose. If you complete this book you will have built the basis of a suite of word processing programs, which will allow simple editing and formatting of text files. You may then extend these to provide some very powerful tools. We shall also look at some simple database tools, which will allow you to store and retrieve information efficiently. The important thing about writing large programs which perform complex functions is to break the design into sections which perform sub-tasks and which are simple enough to write easily. Our next examples introduce simple programs, although ones which are more complex than those we have seen so far. On its own each is not very useful, but later on we will use it as a building block in our much more powerful programs. -###A "top down" design +### A "top down" design Soometimes, in explaining the programs we wish to write, we start from simple components and work towards the whole system. This approach is known as "bottom up" design, for fairly obvious reasons. Where we are only designing a small part of our "grand design" this approach is sufficient. There are not too many components to hold in our heads as we build up the program. When the system we are designing gets bigger, this approach is not good enough. It would be very difficult to write down now all the parts of our formatting and editing system in this kind of detail, especially as we have not said exactly what we want the system to do. It is much more sensible to start at the highest level, with our overall system, and break this down step by step until we reach components which are simple enough to write in SIMULA in detail. This approach is called "top down" design. @@ -108,10 +108,10 @@ We shall fill in other branches as we learn more of SIMULA's capabilities. In fa One last point about top down designs: in reality it is impossible to start with a complete plan, along the lines shown, and write the final program from it. The process of implementing the program in SIMULA will show errors in it and suggest better solutions to some problems. Thus, we can change the design in the light of experience, but we should never change the program without making the same changes in the design. It is surprising how quickly you can forget what the program really does if you have not got a clear description of it. It is even worse if someone else has to look after a program written by you. Since we are writing "real" programs, we must do the job properly. -###Some simple starting points +### Some simple starting points We are going to write some programs now which can be extended to perform some of the functions associated with components in our plan. In fact they may prove useful in other places in the system as well. There are two that are simple to write using if statements and if-then-else statements. One will check if a text starts with a double blank and remove one blank if it does. The other will check if a line is longer than 60 characters and split it if it is. -###Double blank removal +### Double blank removal This problem is easy to describe in English. We have a text variable, which may contain any number of printing characters (we assume no non-printing characters are present). If the first two of these are spaces (ISO blank characters) we want to remove one of them, to leave a shorter text. A good way of writing programs is to write them in SIMULA as far as we can at the moment and to describe any parts which are missing in English. The program in example 4.4 shows this, with the genuine SIMULA parts in normal letters and the informal English descriptions in italics. @@ -223,7 +223,7 @@ Example 4.7: Complete double space remover. OutImage end Double space remover Do not worry too much if this is not completely clear at first. With a little study you should get an idea of what is happening. An even better idea is to try compiling and running this program. Try various combinations of spaces at the start of the input you use. -###Exercises +### Exercises 4.1 Try compiling and running the program below. begin @@ -255,7 +255,7 @@ Change this program so that whatever value is assigned to T it will not cause a comment But all it does is print blank lines; OutImage end of greeting -###Line breaker +### Line breaker Our second example breaks lines at a length of 60 characters. It is rather crude, but we can improve it. This is another development technique which is widely used - stepwise refinement. Stepwise refinement works by getting part of the job working and moving, one step at a time, towards a complete solution. Again we start with an informal half SIMULA description, in example 4.8. @@ -282,7 +282,7 @@ You have probably also noticed the comparison and the new symbol it uses, >. Thi We are left to fill in the actions when the length of the line is greater than 60 characters. One immediate problem is that more than one action is required, yet only a single statement is allowed in this place in the if-then-else statement. Fortunately, we have already seen the answer. -###Compound statements and blocks as statements +### Compound statements and blocks as statements If you think back I mentioned that a block in SIMULA can be used as a statement. More generally, we can use a sequence of statements enclosed in begin and end wherever we can use a simple statement. In fact SIMULA uses the term "compound statement" for such a sequence if it contains only statements and the term block where it contains its own declarations. Let us rewrite our program using each in turn to see this. First with a compound statement in example 4.9. Note that we have used two new variables, which are only needed within the compound statement. We can rewrite this using a block and declaring these where they are used. This prevents accidental assignment to them elsewhere, since variables declared inside a sub-block are not visible outside of it. They are, however, visible inside sub-blocks which it encloses. In general it is safest to declare variables as close to the point where they are used as is possible. @@ -340,7 +340,7 @@ Here, as promised is a list of the simple relational operators in SIMULA. < lt is less than >= ge is greater than or equal to <= le is less than or equal to -###Summary +### Summary We have seen the use of if and if-then-else statements to enable choices within our programs. We have seen how top down design works and begun to outline the software that we shall build as our practical work in this book. Using if and if-then-else statements we have written programs which will form the basis for some parts of our system - double blank removal and line breaking. @@ -351,7 +351,7 @@ We have seen how to replace simple statements with compound statements and block {{ book.Chapter5 }} -###Exercises +### Exercises 4.7 Extend our line breaking program to cope with lines longer than 120 characters. 4.8 Could we extend the program to cope with lines even longer than this? How does this fit in with the problem in 4.5? \ No newline at end of file diff --git a/en/Chapter5/README.md b/en/Chapter5/README.md index 0cfa3a1..4fabfd9 100644 --- a/en/Chapter5/README.md +++ b/en/Chapter5/README.md @@ -1,8 +1,8 @@ -#Chapter 5 - Would you mind repeating that? +# Chapter 5 - Would you mind repeating that? -##Texts and while loops +## Texts and while loops -###Don't stop until I tell you +### Don't stop until I tell you In the last chapter we twice considered the question of how to extend programs which assumed a maximum number of repeated tests, so that any number could be dealt with, as the data required. I hope you managed to deal with triple spaces and triple length lines without too much trouble. Obviously it would be more of the same to cope with four spaces or lines longer than 180 characters and so on. But how can we cope with any number of repetitions? This situation is obviously going to crop up in most real programs. To deal with it SIMULA has a statement known as a while loop. Example 5.1 shows it in use. @@ -41,12 +41,12 @@ The simplest is where the first number is negative. In this case the condition N Another possible stream is one positive number followed by a negative number. Here the condition is true the first time and the number is added to Total. When the next number has been read the program moves back to while. This time the condition is false and so the statement after do is skipped this time and the total will be the value of the first number. -###Exercise +### Exercise 5.1 Work through the case where two positive numbers are input, followed by a negative one. It is known as "dry checking" when you try the program "by hand" in this way. Compile and run the program to make sure you were right. -###Line breaker revisited +### Line breaker revisited We can now extend our line breaker to deal with any length of line. Let us write it out informally, to get our design right. The important things to consider when writing programs using while loops are: @@ -113,10 +113,10 @@ Example 5.4: Linebreaker 2. end This time I have used a more concise way of printing the first 60 characters and, since Image takes the place of Second in the examples in chapter four, no extra text variables are used. -###Exercise +### Exercise 5.2 Are there any line lengths which are not catered for? If you can think of any, modify the program to cater for them. -###What is a text? +### What is a text? In the last chapter we saw some properties of text, which make it a much more complex type than integer, for example. Let us consider further what exactly a text is and what properties it has. In fact it is so complex that we shall only look at half of its properties here and leave the rest until chapter 8. So far we have seen that a text has a string of characters. This may be of any length from zero to some very large number. The maximum length is system dependent and you should consult the User's Guide or Programmer's Reference Manual for the SIMULA system you are using. It is unlikely to be too small for you. @@ -125,17 +125,17 @@ We have also seen that a text contains procedures, which are inside it or "local Strictly speaking the location reserved for the text variable holds a reference to a sequence of characters. These characters are known as a text frame. A text reference contains a pointer to its text frame plus related variables and procedures. The use of these will, hopefully, soon become clear. -###A text reference +### A text reference The variables inside a text reference are not visible outside it. They are used by the procedures which form the visible attributes of a text, along with the text frame. Here are the major parts of a text, with examples of their use. -###Text frame +### Text frame The value part of a text is the string of characters to which its reference variable points. This is known as the text frame referenced by that variable. It is a location in the computer's memory holding a sequence of characters and has a fixed length. Two text frames may overlap and share some part or all of the same sequence of characters and, by implication, of the same location. -###Length +### Length The length of the string of characters in the text frame is held in a hidden integer in the text reference variable. Its value can be obtained by calling the local integer procedure Length. We have used this in some earlier examples to find the length of a line of input. Example 5.5: Use of Length @@ -148,7 +148,7 @@ Example 5.5: Use of Length OutImage end Note that the name given to the integer is irrelevant to the call of Image.Length. I have called it Length to demonstrate that the procedure Image.Length is different from any use of Length on its own, in the program itself. -###Pos +### Pos The position of the character which will be read next in the text frame is held in another hidden integer variable within the text reference. It can be read by calling the integer procedure Pos. When a text object is first created Pos will give the value 1. After calling GetChar for the first time it will give 2 and so on. Example 5.6: Use of Pos. @@ -168,7 +168,7 @@ You should get 1 2 as output when you run this. -###More +### More More tells you when you have reached the end of a text. It returns either true or false, i.e. it is a Boolean procedure. More gives the value true as long as the value given by Pos is between 1 and the value given by Length. Thus, once the last character has been read, More returns the value false. @@ -190,7 +190,7 @@ When you run 5.7 you should get output of the following form. 3 4 etc. until Image.Length -###Constant +### Constant Boolean procedure Constant is a late addition to the definition of text. It returns the value false unless the text frame for its text reference is non-writeable, in which case it returns true. Only text frames generated by reference assignment of a constant string (see below) or sub-texts generated from these will cause Constant to return True. Any attempt to alter the contents of a text frame whose reference returns true for Constant will cause a runtime error to be reported. As a very new feature, Constant will not be recognised by many older systems. @@ -204,7 +204,7 @@ Example 5.8: Use of Constant. T :- Copy("Writeable"); if T.Constant then OutText("Wrong") else OutText("Correct"); end -###Sub and Start +### Sub and Start We have already used Sub. Sub returns a reference to a text frame made up of a sequence of characters which are part of the original text. It has two integer parameters. The first specifies the number of the character in the original text frame which will be the start of the subtext. The second specifies the number of characters which will be in the subtext. Example 5.9 will print out the following: @@ -246,7 +246,7 @@ Example 5.10: Use of Start. OutInt(T3.Start,4); ! 3+3-1=5; OutImage end -###Text assignments +### Text assignments The oddest thing about texts is that there are two different kinds of assignment statement, using two different assignment operators. We have already used both, but now we can explain their differences. There are text reference assignments and text value assignments. Examples are: @@ -295,13 +295,13 @@ c) Left hand text shorter than right. OutText(Left);OutImage; OutInt(Left.Length);OutImage end -###NoText +### NoText When you create a text variable it is set to point to NoText. NoText is an imaginary text frame with no characters. Thus it has a Length of zero and any value assignment to it will fail, except when the value is the empty text value, "". This is the reason we had to use Blanks in our early examples, to make what you should now recognise as a text reference assignment to any text variable, before any value assignments were made to it. -###Creating text objects +### Creating text objects In general, we must make a reference assignment to a text variable before we use it for almost anything else. This points it at a text frame and sets the values for Pos, Length etc., but where does this object come from in the first place? In fact we have used several methods of text object generation already, without explaining them in detail. Here is a more detailed look. -###Blanks +### Blanks The standard procedure Blanks creates a new text object containing only spaces. It has one integer parameter, which specifies the number of space characters it is to contain and, thus, sets its Length. Start and Pos will initially be 1. More will be true. Constant will be false. Example 5.12: Use of Blanks for text generation. @@ -313,7 +313,7 @@ Example 5.12: Use of Blanks for text generation. OutInt(Empty.Length,4); OutImage end -###Reference assignment of text constants +### Reference assignment of text constants We have seen how text constants, or strings, are represented. When a text reference assignment, whose right hand side is such a constant, is made, a text frame is created containing the characters in the string. One important property of the text frame created in this way is that it is regarded as constant or "read only". Any attempt to overwrite its characters will cause a runtime error. @@ -330,7 +330,7 @@ Example 5.13: Text constant reference assignment. OutInt(Full.Length,4); OutImage end -###Copy +### Copy In older SIMULA systems, this reference assignment of text constants was not allowed. If you are using such a system you will have to use the standard procedure Copy to do the same thing. Copy will still work on newer systems, so if you may need to move your programs around a lot it might be safer to use it from the start. Copy differs from constant text reference assignment in that the text frame created is alterable or "writeable". It is possible to overwrite its characters. Thus Copy may be used for many purposes where text reference assignment of constants would not be suitable, even on newer systems. @@ -352,14 +352,14 @@ Example 5.14: Text generation using Copy. OutInt(NewFrame.Length,4); OutImage end -###Line breaker again +### Line breaker again Using the facts about reference assignment of text variables that we have just seen, it is possible to write our line breaking program more neatly. It should now be obvious why we used the integer LenLeft to hold the length of Image which remained. It is now possible to use Image.Length instead. This version has another advantage, which probably is not apparent. In the version using value assignment, the Length of Image remains unchanged throughout, with more space characters following the visible characters after each assignment of Image.Sub. These characters are not present after the reference assignments in the new version. Since some output devices make a printing movement even for a space, their presence may slow down output. They also take up space in the computer's memory which is freed in the new version. Example 5.15: Linebreaker using reference assignment of texts. -begin + begin InImage; inspect SysIn do begin @@ -375,7 +375,7 @@ begin OutImage end end -###Exercises +### Exercises We have had quite a lot to absorb recently, so here are some examples to help your digestion. Then we will have another look at space removal and a final look, for the moment, at text objects. 5.2 Write a program to draw a Christmas tree, like the one below. @@ -406,7 +406,7 @@ We have had quite a lot to absorb recently, so here are some examples to help yo using parts of the string "May Charlie stay for curry?". 5.8 Is it possible to rewrite the word counting program to allow full stops (periods) and commas to be word separators? What extra SIMULA facility would be useful for this? -###Double blank remover, mark two +### Double blank remover, mark two The problem with our double blank removing program is that it will only work when the double blank is at the start of the text. What we really need is a program to read along the whole of a text and remove any double blanks. Even better, it should remove treble and other multiple blanks as well. Using our informal SIMULA description method, we can start with the program in example 5.16. @@ -486,7 +486,7 @@ Try following some texts through the program on paper. In particular try to thin We still have two parts of the program to fill in. Before we can do so we must look at some more properties of text objects. -###GetChar and PutChar +### GetChar and PutChar We have seen how GetChar works, but let us quickly define exactly what it does. GetChar returns the character at the current position in a text and increments the position counter by one. Thus successive calls on GetChar will scan through a text character by character. PutChar overwrites the character at the current position in a text with the value passed to it as a parameter. It has a single character parameter. It increments the position counter by one each time it is called. @@ -511,7 +511,7 @@ Example 5.18: Text concatenation using GetChar and PutChar. OutImage end end -###SetPos +### SetPos One of our problems in our space removal program is solved immediately by the procedure SetPos. This takes one integer parameter. SetPos resets the current position in a text to the value passed to it as a parameter. Using this we can rewrite our text concatenation program more simply. Example 5.19: Text concatenation with SetPos. @@ -532,7 +532,7 @@ Example 5.19: Text concatenation with SetPos. OutImage end end -###Strip +### Strip Another small problem is solved by the procedure Strip. This returns a text reference to the original text with any trailing spaces, i.e. any spaces at the right hand end of the text, removed. Try the program in example 5.20 to see this at work. Example 5.20: Use of Strip. @@ -546,7 +546,7 @@ Example 5.20: Use of Strip. OutInt(T.Length); OutImage end -###Main +### Main The last part of a text object that we need to consider at this point is the procedure Main. When a text variable is pointed at a subtext, by using Sub or Strip, the result is that the text variable points at a new text frame. This shares some of the characters in the original, main text, but has its own local Pos, Length and other attributes. Pos will be 1 and Length will be the length of the subtext. @@ -610,7 +610,7 @@ Example 5.22: Adding SetPos and Strip to multiple space deletion. OutImage end end -###Multiple spaces finally removed +### Multiple spaces finally removed First consider example 5.22, where SetPos and Strip are added to our program. We have now catered for everything except the actual deletion process. Example 5.23 adds the final stage,the removal of those blanks. Watch closely, as we are going to use a very powerful property of text reference assignment. @@ -662,7 +662,7 @@ Example 5.23: The complete multiple space remover. The point to note is that when the text variable T2 is pointed at the text frame already pointed to by T, the effect is that a new reference is created with all its current values the same as T. As in a subtext, some of the characters are shared by both frames; in this case it is all the characters which are shared. When T.GetChar is used, it is only the Pos of T that is affected. That of T2 is unaffected. When we are shuffling the characters to the left to remove unwanted spaces, we are able to pretend that T and T2 are entirely different texts. If we did not do this, we would have to copy into another text frame and then back again. This way of manipulating the characters in a text is very powerful, but must be fully understood and used with great care. It is only when the part of the text that we are copying from is ahead of the part that we are copying to that this method will work. -###Summary +### Summary We are now writing programs which really do things. In this chapter we have seen the while loop and how it can allow an action or sequence of actions to be repeated as often as necessary. @@ -681,7 +681,7 @@ We have seen how two text variables pointing at the same sequence of characters {{ book.Chapter6 }} -###Exercises +### Exercises 5.9 A computer fault has changed some small letter a's into ampersands, '&'. Write a program to scan a text and correct this. 5.10 A similar fault has changed every occurence of the word "and" to the word "boe". Write a program to correct texts which have suffered this fate. \ No newline at end of file diff --git a/en/Chapter6/README.md b/en/Chapter6/README.md index c03a3ca..e758039 100644 --- a/en/Chapter6/README.md +++ b/en/Chapter6/README.md @@ -1,13 +1,13 @@ -#CHAPTER 6 - Correct Procedures +# CHAPTER 6 - Correct Procedures -###Building blocks +### Building blocks We have written some programs which do real work, but at the moment they have to be run separately, with the input provided for each run. It is not obvious how we can use such separate programs to build a large, flexible piece of software. One method would be to combine all the small programs that we write into one large program, using each program in the right order. We could use our multiple space removing program, followed by our line breaking program and so on. This is fine for programs that only need to be used in one place, but if the same function is required in several places we will need to duplicate the instructions each time. This is inefficient, making our programs much longer than they need to be. It can also make it tedious to follow the overall working of a large program, since a mass of detailed instructions tend to obscure the important features of the design. As an example of a program which could be used in many places in our package, we might take the text concatenation program. In fact this is such a useful thing to be able to do that we might wish that a language feature existed for it. In fact, such a facility is now provided as part of SIMULA. Unfortunately, it is not yet available in most systems. We shall see it in chapter 8. Fortunately, we are able to define our own procedures, which we can then use wherever we like inside the block where we declare them. In fact we can even build a library of our favourite procedures and use it in all our programs. -###Declaring procedures +### Declaring procedures It is clearly not enough to declare a procedure in the way we declare an integer. The declaration @@ -55,7 +55,7 @@ Example 6.2: Concatenate as a procedure. end; Concatenate end -###Parameters to procedures +### Parameters to procedures This Concatenate procedure only joins texts which are read in by it. Having done so, it merely prints out the result. This would be much more useful if we could use it to combine any two texts in our programs and to assign the result to any text we chose. This can be done by specifying parameters in the declaration. We have already seen how parameters can be used to pass values to system procedures. Example 6.3 shows how to declare two texts as parameters to the Concatenate procedure. @@ -96,7 +96,7 @@ Example 6.4: A procedure with more than one type of parameter. TextAndInt("NUMBER",10) end When execution of a procedure is complete all quantities declared inside it are lost. This includes the final values of its parameters. The remaining question is how to get back the text containing the concatenated texts once Concatenate is complete. There are two ways of doing this in SIMULA and the first of these uses a different sort of parameter. -###Parameter modes +### Parameter modes The way of specifying parameters that we have used so far will always work for passing values into a procedure. If we want to get information out, we may have to add a mode specifier for some parameters. This sounds confusing, but is easy to follow in practice. Here is a final version of Concatenate. @@ -142,7 +142,7 @@ A simple type is integer, real, character or Boolean and any long or short varia Now we can see that name is always legal and reference is the default for all but simple types. Do not worry about the meaning of those types which are new. We shall consider their use when we encounter them. -###Value parameters +### Value parameters A value parameter to a procedure acts as if it were a variable of that type declared in the body of the procedure. The value passed to it when the procedure is called is copied into it as part of the call statement. Since values declared inside a block cannot be used outside that block, the value of this mode of parameter is lost on returning from the procedure. When calling a procedure, any value of the correct type may be passed to a value mode parameter. Thus constants, expressions and variables are all allowed. @@ -192,7 +192,7 @@ Example 6.7: Text parameter passed by value. OuterT:-"Here's a line"; OutLine(OuterT) end -###Reference parameters +### Reference parameters When a parameter is passed by reference, the local parameter points at the location holding the object passed, rather as if the :- reference assignment operator had been used. No local copy is made of the contents of the object. For every reference parameter type except text, this explanation is sufficient and should be reconsidered for its meaning when those types are encountered. @@ -229,7 +229,7 @@ Example 6.8: Concatenate using only reference mode parameters. OutText(Text3); OutImage end -###Name parameters +### Name parameters Name parameters are very powerful, but complex. It is sometimes possible to make serious errors using them, through failing to consider all possile outcomes of their use. When a variable is passed by name, its use within the procedure has the same effect as when that variable is used outside the procedure. Thus any actions on the parameter inside the procedure directly affect the variable passed in the call. This is obviously a suitable mode for getting values back from a procedure, as we have seen. @@ -287,7 +287,7 @@ Example 6.10: Expressions by name and by value. Use_Name(OuterVal+3,OuterVal+3) end++of++program -###Exercises +### Exercises 6.1 Write a program which uses a procedure to find the larger of two numbers and returns it in a name parameter. 6.2 Write a program which uses our multiple space removal program as a procedure. Devise a series of tests to cover all the cases you can think of which this procedure might have to cope with and try them. Do not use lots of tests which all check the same thing, but try to use one good test for each possibility. @@ -298,7 +298,7 @@ Example 6.10: Expressions by name and by value. 6.5 Write and test a procedure which counts the number of non-space characters in a text. -###Functions +### Functions There is another way to return values from procedures to the calling block. We have already seen examples of system procedures which use this mechanism in GetChar and InInt. Now let us see how to write procedures for ourselves. Example 6.11 is an example of such a procedure which adds two numbers together and returns the result. Such a procedure is usually referred to as a "type procedure" or, most commonly, a "function". @@ -348,7 +348,7 @@ Example 6.12: Concatenate as a text procedure. OutText(Concatenate("PART ONE"," PART TWO")); OutImage end -###Exercises +### Exercises 6.6 Write and test a function which returns the amount of tax payable on an income and which takes three parameters - the tax free allowance, the rate of taxation and the amount earned. 6.7 Use the function to write a program which calculates the tax on a person's income, assuming the following rates. @@ -374,7 +374,7 @@ Reads in and performs the following commands: one. S - move back to the start of the text. E - end further command processing and print the final text. -###Recursive procedures +### Recursive procedures A procedure must be declared inside a block. Like any other declared item program, it may be used anywhere within that block. This includes using it within blocks and procedures which are also within that block. In a block which has more than one procedure declared within it, any one of these procedures may be called inside any or all of the others, even those which are declared before itself. This is known as the scope of such a declaration. This has one rather important implication. A procedure may make a call on itself. This as known as a "recursive" call. 6.13 is an example of a program which uses a recursive procedure call. @@ -411,12 +411,12 @@ If the character read is a space, Non\_Blank is called again and the text is pas showing clearly the two uses of Non_Blank as left side of an assignment, returning the value for the function, and as recursive call, with parameter. Try working through for yourself using texts with various numbers of spaces at their start. Once you have seen how it works for a couple of examples you should get the idea. -###Text function results and recursion +### Text function results and recursion A text procedure returns a text reference. Thus only reference assignments to the procedure identifier, witthin the procedure body assign a new result. Value assignments merelyalter the contents of the text frame of the currently assigned reference. When the procedure identifier occurs on the right hand side of an assignment the effect is independent of whether it is a reference or value assignment. Such an occurence is always taken as a recursive call. -###Dangers of recursion +### Dangers of recursion It is not necessary to have a type procedure to use recursion. There are many instances when non-type procedures can use recursion. It is a vey powerful device. Example 6.14 uses a non-type procedure . It shows the power of recursion and the possible problems of using it without proper thought. Example 6.14: The danger of non-terminating recursion. @@ -438,7 +438,7 @@ If you are not sure what is wrong, look carefully at the call on Numbr inside th In general, recursive calls must only be made as part of an if statement or an if-then-else statement and the condition for their being called must become false at some point. This requires some care, but is no more of a problem than writing while loops which stop at the desired point. In fact recursive calls and while loops are very similar. -###Summary +### Summary We have seen how to declare and call simple procedures, with and without parameters. We have seen how to specify the types of any parameters to a procedure. @@ -453,7 +453,7 @@ We have learned how to use simple recursion. {{ book.Chapter7 }} -###Exercises +### Exercises 6.11 Use a recursive procedure to write a program which scans a text for a occurences of a sequence of characters and replaces them with another. 6.12 Use a recursive procedure to write a program which reads in lines of text and prints them out with a line number. Set the program to stop when the line diff --git a/en/Chapter7/README.md b/en/Chapter7/README.md index 098597a..22ef1e4 100644 --- a/en/Chapter7/README.md +++ b/en/Chapter7/README.md @@ -1,8 +1,8 @@ -#CHAPTER 7 - File FOR future reference +# CHAPTER 7 - File FOR future reference -###Simple input and output using InFile, OutFile and PrintFile +### Simple input and output using InFile, OutFile and PrintFile -###Storing and retrieving information +### Storing and retrieving information So far we have been limited in what our programs can do by the need to read everything in from the terminal or batch input stream and write everything out to the terminal or batch printer. This means that our SIMULA programs have not been able to use information already held on the computer or to leave information on the computer for other programs to use. This chapter will show how SIMULA provides very powerful mechanisms for this purpose. You are probably used to the fact that computers keep permanent information in collections called files. Some systems use other names such as data sets, but they are essentially the same thing. These files have names by which you can identify them to the computer. Programs can read from these collections of information and write to them. @@ -13,7 +13,7 @@ In fact a SIMULA File can stand for any source of or destination for information In fact you have already been using two File objects without being told that that was what you were doing. These are the standard input File, SysIn, and the standard output File, SysOut. Whenever you have used InInt, OutImage and any other input/output instructions you have been using File attributes. -###Simple input +### Simple input To read information from the computer we normally use a type of File object known as an InFile. In fact InFile is a sub-class of the object type or class called File. This means that all the properties of File are properties of InFile or are redefined in InFile, but that InFile has some extra ones of its own. In fact all types of File objects are sub-classes of File. InFile is not a direct sub-class of File, however; there is another level between them, called ImageFile. Put more simply, class File defines a type of object with a number of attributes used to access sources of and destinations for information on a computer, such as files, printers, terminals and tape readers. @@ -62,7 +62,7 @@ Most of the rest of the program should be familiar, except for the prefixing of The final statement calls the procedure Close, to tell the SIMULA system that this File is not required until Open is called for it again. -####Simple output +#### Simple output Corresponding to InFile, but used for output of information, is the class OutFile. This is also a sub-class of ImageFile. Example 7.2 is a simple example of the use of OutFile. It corresponds to the InFile example fairly closely and so no further explanation is given yet. @@ -82,22 +82,22 @@ Example 7.2: Simple output using OutFile. Outf.OutImage; Outf.Close end -###Exercises +### Exercises The information you have about output to files should now be sufficient to allow some simple attempts at reading and writing to files. This is mainly intended to familiarise you with the way in which your particular computer and SIMULA system treat the File objects in SIMULA programs. You should read the documentation for your system carefully at this point. 7.1 Write a program which prints the integer values 1, 2, 3 and 4 to an OutFile. Check what sort of File your system has created on the computer. See if you are able to examine its contents and list them to a printer. 7.2 Write a program which reads the contents of the File produced in 7.1, using an InFile, and writes it to the terminal or batch output stream. -###ImageFile class InFile +### ImageFile class InFile Having seen informally how input and output are handled in SIMULA, let us now consider three of the four sub-classes of ImageFile and what they do, starting with InFile. We shall not consider all the attributes of class InFile here. Some will be dealt with in {{ book.Chapter8 }}. The remaining sub-class will be dealt with in {{ book.Chapter15 }}. -###Image +### Image All ImageFile derived File objects use a text in their reading or writing. This represents the current input/output line or record. Files using this mechanism are called "record oriented". This means that a whole record is read into the Image text or written from it at a time. Most attributes of an ImageFile object operate on the copy in Image, not the actual File or device it stands for. Image is a text variable within the ImageFile object. In an InFile, the parameter passed to Open is used initially as its Image, i.e. is assigned by reference to Image. This is usually an anonymous text created by giving the text generator Blanks as the parameter to Open. The number given as parameter to Blanks determines the length of Image and should match the record or line length of the external file or device. Where the external record length is not fixed, the length of Image should be the maximum record length possible or expected. -###Open +### Open Open is actually a Boolean procedure. If the attempt by the SIMULA runtime system to find and access the external file specified is unsuccessful, Open will return the value False. This can happen if the external file does not exist, is not permitted to you or for a number of reasons which are system dependent. Any attempt to read from the File subsequently will result in a runtime error. Older systems will have Open as a type-less procedure and attempting to open a file which is not available will cause a runtime error on these systems. @@ -108,12 +108,12 @@ Open also assigns its text reference parameter to Image, creating a "buffer" tex A successful call on Open will return the value True. -###IsOpen +### IsOpen IsOpen is a Boolean procedure. It returns false if the File is not currently open, i.e. no call of Open has yet been made or the File has been closed. Open sets IsOpen to true. Close sets IsOpen to false. Older systems may not have IsOpen as a File attribute. -###SetAccess +### SetAccess Modern SIMULA systems allow programs to specify certain modes for open files. The exact meaning of these will depend on the physical file system of the computer. Each file used will have initial properties, some of which are defined in the SIMULA standard. These will be found in the documentation for the system you are using. A summary is given in table 7.1. All SIMULA systems which meet the current standard will allow files with the following properties. @@ -145,7 +145,7 @@ Table 7.1: Default modes for file types. Bytesize:n * * * Open Rewind norewind norewind N/A Open/Close Purge nopurge nopurge nopurge Close -###InImage +### InImage The procedure InImage copies the next record from the external file or device into Image. This is equivalent to a text value assignment. If the external record is shorter than Image.Length then it is copied into the leftmost character locations in Image and the remaining character Positions are filled with spaces. If the external record is longer than Image.Length, calling InImage causes a runtime error to be reported. InRecord @@ -157,26 +157,26 @@ Where the external record is longer than Image, only enough is read in to fill I Where the lengths are the same InRecord acts exactly as InImage, but returns false. -###Close +### Close Boolean procedure Close tells the SIMULA system that the external file or device represented by this File object is no longer required by it. This means that it can be used by another File object. Thus, once an InFile has been closed, it can be reopened as an OutFile. Once an external file or device has been released in this way it may also be claimed by other programs and users. If an attempt is then made to reopen it using the original File object, a runtime error may result. If Close is unable to perform its task, it returns false. Otherwise it returns true. Older systems will only have Close as a type-less procedure. If a File is left open at the end of a program, it will be closed by the runtime system, with a warning in most systems. It is safer to close files in the program. -###SetPos +### SetPos This procedure is equivalent to Image.SetPos. -###Pos +### Pos This integer procedure returns Image.Pos. -###More +### More This integer procedure returns Image.More. -###Length +### Length This integer procedure returns Image.Length. -###EndFile +### EndFile This is a Boolean procedure. When the last character of the last record in the external file has been read it returns the value True, otherwise it returns the value False. Example 7.3 shows of the use of EndFile to read and print the whole of a record structured File. @@ -202,7 +202,7 @@ Example 7.3: Use of EndFile. end end -###LastItem +### LastItem LastItem is a Boolean procedure, rather like EndFile. It returns False as long as there are any non-space characters left in the File. It will skip any spaces, updating Image and Pos, until it finds a non-space or the end of the File. If it has reached the end, it returns True; if it finds non-space characters, it returns False. Example 7.4 is a word counting program which uses LastItem. @@ -257,10 +257,10 @@ Example 7.4: Use of LastItem in word counting. OutImage; Words.Close end -###Item oriented input +### Item oriented input Some procedures read in the sequence of characters in the real file as an item of a certain type. Most are described in {{ book.Chapter8 }}, but here are two useful ones. -###InChar +### InChar InChar is almost the same as Image.GetChar. It is a character procedure which returns the next character in the File. If the end of the current Image has been reached, i.e. Image.More returns False, InImage will be called and the first character in the new Image read. Since SIMULA specifies that a call on InImage once the last record of the real File has been read will place the ISO end of file character, !25!, as the first in Image. A call on InChar once the last character of the real file has been read will return this non-printing character and EndFile will then return True. If the end of the File has been reached, i.e. EndFile returns True, a call on InImage will cause a runtime error. We can rewrite our word counting program, using InChar to replace Image.GetChar, as shown in example 7.5. @@ -315,7 +315,7 @@ Example 7.5: LastItem and InChar in word counting. OutImage; Words.Close end -###InText +### InText InText is a text procedure, with a single, integer value parameter. Its result is a text containing the next N characters in the real file, where N is the value of its integer parameter. It may include characters from more than one record in the real file, calling InImage as necessary. Example 7.6 is a new line splitting program, using InText. Note that it assumes an input file with lines 132 characters long. Note also that it does not deal with blanks at the end of Image. @@ -333,40 +333,40 @@ Example 7.6: Line splitting with InText. end; OldLines.Close end -###ImageFile class OutFile +### ImageFile class OutFile OutFile is the output equivalent of InFile and so has some similar attributes and some which are the output equivalents of InFile's input attributes. Again, some will be left until chapter 8. EndFile and LastItem do not exist for OutFile, since they would have no meaning. -###Image +### Image The Image text of an OutFile is set up in the same way as that of an InFile. It is used to accumulate items which are to be output, until a call of OutImage or OutRecord writes the current line or record to the real file or device. -###Open +### Open Boolean procedure Open works in approximately the same way as for InFile, except that the real file or device is reserved for output, not input, and the real file may be created if it does not exist already. The text reference parameter is used as the initial Image, as in InFile. -###IsOpen +### IsOpen IsOpen works in exactly the same way as it does in InFile. -###SetAccess +### SetAccess SetAccess works in exactly the way as it does in InFile. -###OutImage +### OutImage When OutImage is called either, explicitly, from the program or, implicitly, by one of the item output routines like OutChar, the current contents of Image are written as a new record to the file or device connected to this OutFile. Image is then filled with spaces as if by Image :- Blanks (Image.Length); -###OutRecord +### OutRecord Procedure OutRecord works in a similar way to OutImage, but only writes out those characters preceding Pos in Image. Thus OutRecord can be used to create files with variable length records, where the operating system supports this. Older systems will not have OutRecord. -###BreakOutImage +### BreakOutImage Procedure BreakOutImage writes out the contents of Image in the same way as OutRecord, except that it does not produce any implicit line terminator. Thus successive calls of BreakOutImage will write a series of Images to the same line. It is intended to allow prompts to be displayed on interactive terminals, in a manner that allows input to be typed on the same line. Where an operating system does not support output without line terminators, BreakOutImage is exactly equivalent to OutRecord. Older systems will not have BreakOutImage. -###Close +### Close This procedure is the same as for InFile, except that, if the Image is non-empty at close, i.e. Image.Pos is not 1, there remain some unwritten characters. In this case, Open calls OutImage to write out the remaining record. Again, files will be closed automatically at the end of the program, although it is tidier and safer to close them in the program. @@ -375,7 +375,7 @@ This means that the programs 7.7 a, b and c are equivalent. It is much safer to call OutImage and Close explicitly, when they are needed. Consider the effect of extending the program to do further writing to Out1, if you are depending on the end of the program to output the Image containing "SUCCESS". -###CheckPoint +### CheckPoint Boolean procedure CheckPoint is used to safeguard any output done so far. If it is called, the operating system is requested to complete all writing to the external file which may have been buffered or delayed before returning. If this is successful, CheckPoint returns true. If it fails or the operating system does not allow checkpointing, false is returned. Example 7.7a. @@ -424,19 +424,19 @@ Example 7.7c. COMMENT do not call OutImage; end end -###SetPos, Pos, More and Length +### SetPos, Pos, More and Length These are all exactly as for InFile, i.e. equivalent to Image.SetPos, Image.Pos, Image.More and Image.Length. -###Item oriented output +### Item oriented output Several attributes of OutFile are procedures which write out items of various types. Most are dealt with in chapter 8 , but here are the two which match those given for InFile. -###OutChar +### OutChar This procedure takes a single character value parameter. It writes this to the File. If there is space in the current Image, i.e. Image.More returns True, it is written by Image.PutChar, otherwise OutImage is first called and the character is then written as the first in the next record. -###OutText +### OutText This takes a single text value parameter. As with OutChar, if there is insufficient space in Image, OutImage is first called. The characters of the text are copied into Image as if by successive OutChar calls. Pos is thus increased. If the length of the text is greater than Image.Length a runtime error occurs. -###Exercises +### Exercises 7.3 Write a program to remove double spaces from a whole file, producing a new file. Extend this to place a double space after each full stop. 7.4 Write a program to remove blank lines from a file, producing a new file. diff --git a/en/Chapter8/README.md b/en/Chapter8/README.md index b9a65a0..f34a89b 100644 --- a/en/Chapter8/README.md +++ b/en/Chapter8/README.md @@ -1,13 +1,13 @@ -#CHAPTER 8 - Item by Item +# CHAPTER 8 - Item by Item -##Item oriented reading and writing and for loops +## Item oriented reading and writing and for loops -###Reading and writing numbers +### Reading and writing numbers This chapter will consider the mechanisms in SIMULA for translating numbers into sequences of characters within texts and for translating sequences of characters within texts into numbers. This is clearly a useful thing to be able to do. In fact, we have already used some of these features to make our programs possible. Now we will look in detail at the attributes of text and File which are used for this purpose. Essentially, this is an extension of the "item oriented" concept used in describing InChar, OutChar, InText and OutText. Instead of considering a sequence of characters as just part of the text in which they occur, we are going to interpret them as integers or reals. Instead of adding to a text some sequence of characters from another text, we are going to write an integer or a real value as such a sequence. -###Adding numbers to a text +### Adding numbers to a text There are four procedures which are attributes of text and can be used to add sequences of characters, which represent numbers, to the text. In each the number is converted to a sequence of characters, representing its value as the appropriate type. Apart from decimal points where appropriate, there are no spaces, commas or other separators in such sequences, except when using PutFrac. If the number is negative, a minus sign precedes the first digit, with no intervening space. This sequence of characters is added to the text, so that the last character is in the rightmost position in the text. If the sequence added is shorter than the text being used, characters in front of the first character added are filled with spaces. @@ -16,7 +16,7 @@ If the text refers to NoText, the attempt to add the sequence causes a runtime e The current position is moved to the end of the text. -###PutInt +### PutInt PutInt has a single integer value parameter. It converts this value to a sequence of digits representing it as a whole number and adds it to the text as described above. Example 8.1: The use of PutInt. @@ -30,7 +30,7 @@ Example 8.1: The use of PutInt. OutText(T1); OutImage end -###PutFix +### PutFix Oddly, SIMULA uses the name PutFix for the more natural of the two procedures in text which add numbers as reals in texts. As we have seen earlier with OutFix, numbers which are represented as fixed point real numbers consist of a sequence of digits, representing the integer part of the number, followed, if necessary, by a decimal point and a sequence of digits, representing the fractional part of the number. PutFix has two parameters, a real value one, which holds the value to be added to the text, and an integer value one, which contains the number of places of decimals to be printed. When the value is converted to a sequence of characters, it is rounded to give the required number of digits after the decimal point. If the required number of decimal places is zero, no decimal point is printed and PutFix acts like PutInt. If the number of significant digits after the decimal point is too small, zeros are added to give the required number. @@ -47,10 +47,10 @@ Example 8.2: The use of PutFix. OutText(T2); OutImage end -###PutReal +### PutReal PutReal represents real values in floating point form. This is useful to scientists, engineers and mathematicians, since it allows very large or very small numbers to be represented. PutReal is described in appendix B. -###PutFrac +### PutFrac SIMULA allows integers to be represented as "grouped items". This is occasionally useful, when representing such things as amounts of money. It also allows orders of magnitude to be assessed at a glance. A grouped item is a string of digits, separated into groups of three by spaces. There may also be a decimal point as a separator, somewhere in the sequence. @@ -78,7 +78,7 @@ Example 8.5: Use of PutFrac. OutText(T5); OutImage end -###Exercises +### Exercises 8.1 Use PutFrac in a program to calculate a weekly wage, where the first forty hours are paid at #2.30 per hour and subsequent overtime at the normal rate plus half. The program should read in the hours worked and print out the wages for normal working, overtime and as a total. 8.2 What would the representation of the following calls be? Write a program to check your answers. @@ -93,7 +93,7 @@ Example 8.5: Use of PutFrac. 8. PutInt(96.7) 9. T :- Blanks(4); T.PutInt(721964) -###Reading numbers from texts +### Reading numbers from texts Corresponding to the procedures for adding numbers to texts as sequences of characters, there are attributes of text which are procedures for interpreting the next sequence of characters, which must have the format used to represent the type required, as a number of that type. In all the following procedures, reading always starts at the first character of the text being scanned. The value of Pos is ignored. @@ -102,7 +102,7 @@ Any spaces and tabs at the start of the text are skipped. Any other characters b The current position in the text is moved one character past the item read. If the text is a constant this change is lost immediately. -###GetInt +### GetInt GetInt is an integer procedure. It takes a sequence of digits and interprets them as an integer value, returning this value. The sequence is deemed to end at the first non-digit or at the end of the text. Only spaces at the start of the sequence are skipped. In example 8.6, you should note the need to use Sub to identify the sub-text remaining after each GetInt. This is because scanning always starts at the first character of the text and so repeated calls of GetInt on the same text will always return the first sequence matching an integer in the text. GetChar, however, starts from the current Pos and so Sub is not needed when it is called. @@ -127,7 +127,7 @@ Example 8.6: Use of GetInt. OutInt(T6.GetInt,4); ! 12; OutImage end -###GetReal +### GetReal Real procedure GetReal is the only way of reading items as reals. It accepts either the format used by PutFix or that used by PutReal. In either case the sequence must be complete. For the fixed point format, which we are considering here, this means that the sequence must be: A simple sequence of digits, as for an integer; @@ -155,7 +155,7 @@ Example 8.7: Use of GetReal. OutFix(R1,3,8); ! 12; OutImage end -###GetFrac +### GetFrac Grouped items, as described for PutFrac, are read in by GetFrac. This is an integer procedure, which returns the value of the grouped item as if it were an integer, ignoring any spaces or the decimal point if it is present. Example 8.8: Use of GetFrac. @@ -171,12 +171,12 @@ Example 8.8: Use of GetFrac. OutFrac(I8,5,20); OutImage end -###Exercises +### Exercises 8.3 Write a program to read a sequence of real numbers, ending with a negative number, and write them as suitably grouped items. The decimal point should be in the correct place. 8.4 Write a program to read the marks obtained in examinations in English, Mathematics, History and French, in that order, for a class of thirty students. The marks will be given as integers, separated with commas between each subject and with full stops at the end of each student's marks. You may assume that each student's marks are on a new line. Extend your program to write out the results in six columns, with appropriate headings. The first four should give the marks for each subject. The fifth should contain the student's total. The last should contain the student's average, to two decimal places. -###Fixed repetition +### Fixed repetition The problem in exercise 8.4 shows a different type of loop to those that we have used before. Your solution will probably have used the while loop that we learned in chapter 5. The while loop is very powerful, allowing us to write loops which continue for as many repetitions as are necessary to complete the task. Yet in exercise 8.4 we usually knew the number of times that we wanted to repeat the loop. This meant using a counter to keep track of how many times the loop had been performed. There is nothing wrong with such a solution, but SIMULA allows us to write the same loops more concisely, using the for loop. Here is the reading part of exercise 8.4, using a while loop and then using a for loop. @@ -289,10 +289,10 @@ b: Using variables as step and limit values. for I1:=I2 step I3 until I4 do OutInt (I1, 3); OutImage end -###A word of caution +### A word of caution The three values obtained from the expressions in the step-until sort of for clause are checked each time round the loop. It is possible to assign to them inside the loop, which will disturb the normal sequence of values. In fact some very "clever" programs have been written to exploit this. It is, however, a very unsafe practice and you should normally be very careful not to change the values except in the for clause itself. If you use type procedures in these expressions you may produce unexpected side effects too. Keep your programs simple if you want them to work. -###for clauses using lists of values. +### for clauses using lists of values. The step-until for clause is very useful when we want to increase or decrease the value of the controlled variable by some constant amount. By using a variable as the step value and altering the value of this during the statement following the do, the change in the controlled variable can be varied, but this is rather dangerous and rarely useful. A simpler means of assigning a series of values, which are not obtainable by repeated additions or subtractions of a step value, is to use a list as the for clause. Consider example 8.13. Example 8.13: for clause with a simple list. @@ -315,7 +315,7 @@ This program will assign the characters in the list to C in the order they are g BEGI BEGIN which is fairly self explanatory. One important point is that non-arithmetic values may be used, such as characters and texts. This is not possible in the step-until form. -###Steps in lists +### Steps in lists The permutations allowed in the for clause are often only of academic interest. We do not need to consider most of them here. If you are really keen to explore them, I suggest that you refer to the SIMULA Standard [1]. It may be useful to note that a step-until contruction may be used as one element in a list in a for clause. This is shown in example 8.14. Try it and see the effect. Example 8.14: Mixing steps and lists. @@ -328,7 +328,7 @@ Example 8.14: Mixing steps and lists. OutImage end end -###Exercises +### Exercises 8.5 Rewrite exercise 8.4 using for loops where possible. 8.6 Write a program to print out the multiplication tables from two to twelve, in the following format @@ -340,15 +340,15 @@ Example 8.14: Mixing steps and lists. 8.7 Write a program which reads in a series of words and prints them five to a line, with a blank line after every six lines. 8.8 Extend your answer to 8.7 to print successively the letters a, b, c, d, e, f before the lines in each block and to number the blocks. -###Item oriented I/O with Files. +### Item oriented I/O with Files. Matching the item oriented procedures for reading and writing in a text are procedures for reading and writing sequences of characters which represent numbers in Files. Those for output are local to OutFile, and thus PrintFile, while those for input are local to InFile. -###Output of numeric items +### Output of numeric items The numeric item procedures in OutFile output are OutInt, OutFix, OutReal and OutFrac. Each has the same parameters as its Put equivalent, plus an additional width parameter, which is an integer and comes after the others. Basically each procedure creates a sequence of characters in the Image of the OutFile, starting at the current position. These are of the same forms as for the corresponding Put procedures, but their positioning is controlled by the width parameter. -###The meaning of the width parameter +### The meaning of the width parameter The width parameter specifies how many characters in the Image will be used by the numeric item. If the actual item is shorter than this width, space characters are added on the left of the item to achieve the required length. Thus the items are said to be "right aligned" within the length of text specified by their width fields, since their last character always fills the rightmost space specified by the width parameter. If the actual item is longer than the width specified, it is not output. Instead a sequence of asterisks of the specified length is printed. This is known as an editing overflow and many SIMULA systems will report the number of such overflows at the end of the program. By not allowing more than the specified number of characters to be output, the alignment of columns of figures is preserved. By printing asterisks, the user is warned that insufficient space was allowed for printing the required values. @@ -377,7 +377,7 @@ Example 8.15: Item oriented output to a File. Close end*of*inspect end -###Exercises +### Exercises 8.9 Rewrite your answer from 8.6 using OutInt. 8.10 Write a program which reads and prints the name, age in years and weight of a given number of people. The program should: @@ -385,7 +385,7 @@ Example 8.15: Item oriented output to a File. ask for and read the number of people to be dealt with. ask for each item in turn for each person. print out each person's details on a separate line, with the columns correctly aligned. -###Input of numeric items. +### Input of numeric items. The input of numeric items is done by InInt, InReal and InFrac. No parameters are required. Each is a procedure of the appropriate type. Thus InInt reads the next sequence in the current Image as an integer, returning its value. InReal reads it as a real, returning its value. InFrac reads it as a grouped item, returning the corresponding integer value. @@ -398,7 +398,7 @@ Example 8.16 shows the input procedures in use. If a number is read which is larger than the largest positive value or smaller than the smallest negative value of the appropriate type which can be held on a particular computer, a runtime error, either integer overflow or floating point overflow, should be reported. If a real value which is too near to zero is read a runtime error, floating point underflow, should be reported. The limits for each SIMULA system are given in the appropriate Programmer's Reference Manual or User Guide. -###Text concatenation +### Text concatenation As we have now completed the attributes of text, a word on the recently introduced text concatenation operator is perhaps appropriate. This operator, &, combines two text frames, producing a reference to a new text frame. The combined text has a frame consisting of a copy of the characters from the text to the left of the operator, followed by a copy of the characters from the text to the right. Example 8.17 shows the use of the concatenation operator. Only up to date SIMULA systems will have this feature. @@ -429,10 +429,10 @@ Example 8.17: Text concatenation operator. OutText(T3); OutImage end -###Exercise +### Exercise 8.11 Rewrite the exam result question using all the new features which are appropriate. -###Summary +### Summary We have extended the idea of item oriented input and output to cover the reading and writing of sequences of characters which represent arithmetic values in texts. We have seen the attributes of text which allow such operations on integer, real and grouped items. diff --git a/en/Chapter9/README.md b/en/Chapter9/README.md index eedeaa2..d0e0286 100644 --- a/en/Chapter9/README.md +++ b/en/Chapter9/README.md @@ -1,6 +1,6 @@ -#CHAPTER 9 - classes as Records +# CHAPTER 9 - classes as Records -###A simple example +### A simple example One very common use for computers in offices today is for printing self-adhesive labels for envelopes. Consider a program which reads in a name and address followed by the number of labels required. We will simplify things by printing our labels underneath one another, one at a time. Using our knowledge of SIMULA so far, we might write the program shown in example 9.1. @@ -131,7 +131,7 @@ Thus, within the inspect statement in example 9.2, the occurences of Nam, Street A full description of remote accessing is given in {{ book.Chapter13 }}. -###Exercises +### Exercises 9.1 Rewrite the labels program, adding an integer attribute to class Lab. Extend the program so that it will: read a label from SysIn, prompting for each attribute in turn, including the integer attribute; @@ -153,7 +153,7 @@ request the user to type in the service required and then perform it, initially add an additional service to find a record according to its works number; add another service to print out all records where a specified attribute has a specified value, e.g. Name=F.Jones; add another service to find a record and update any or all of its attributes and write an updated file. -###Making classes work for themselves +### Making classes work for themselves Classes are objects containing attributes. These may be of any type visible in the block where the class is declared. As we have seen this can allow us to create objects which match the natural groupings of data that we wish to process in our program. This approach is usually called "object oriented" programming. We also saw, when we considered class File and its sub-classes, that it is not just data attributes that a class object can contain. The power of the class concept as a way of representing objects in our programs is considerably increased by the ability to define procedures as attributes of classes. @@ -363,7 +363,7 @@ Example 9.5: Inserting a numbered label using procedure attributes. OutLine(Source); ! Name of last Output file used; end*of*program -###Making classes work even harder +### Making classes work even harder Procedures as attributes make it possible to embed sequences of actions inside classes. This removes the need for tedious reprogramming of these sequences every time they are used in the main program. Having designed and implemented the class attributes, their internal details can be forgotten. Another mechanism can save even more tedious work. Often the first actions performed on a new object of a particular class follow the same pattern each time one is created. Typically they involve setting the initial values of the data attributes of the object. In class Lab we made this much easier by writing ReadLabel in the definition of the class. This meant that creating and initialising the data in a Lab object required only two statements. By using a simple extension of the class declaration of Lab, we can do it in one. @@ -438,7 +438,7 @@ Example 9.6: Parameters and initialisation Code in classes. Label1 :- new Lab(True); ! Use prompting; Label1.WriteLabel end..of..program -###Summary +### Summary In this chapter we have seen how a programmer can define his or her own complex object types, using structures composed of simpler types. The SIMULA feature which is used for this is the class. We have seen that procedures may also be attributes of classes. @@ -455,7 +455,7 @@ Lastly we have seen the use of parameters to classes. The types and modes allowe {{ book.Chapter10 }} -###Exercises +### Exercises 9.3 Extend the definition of a label object to describe a letter to someone. Data should include name and address of both sender and recipient, text of the letter, date and method of sending, e.g. surface or air mail. You may assume any suitable maximum number of lines for the text. Write a program which reads in a letter and prints it along with a label for mailing it. What problems would occur if the letter had to be able to contain a large and unspecified number of lines? diff --git a/zh/Chapter1/README.md b/zh/Chapter1/README.md index 0255698..cdec568 100644 --- a/zh/Chapter1/README.md +++ b/zh/Chapter1/README.md @@ -1,8 +1,8 @@ -#第一章 +# 第一章 -##开始之前的话 +## 开始之前的话 -###程序是什么 +### 程序是什么 一段计算机程序(program通常是按美式英语拼写的)是一系列包含了完成一些任务所必需信息的指令。这类似于织布针法,食谱或音乐总谱。同时计算机程序也使用一种特殊的描述方法,即编程语言。 @@ -37,17 +37,17 @@ begin和end被称为关键字,因为它们有特殊的用途不能用于做其他事情。 -###关于字母大小写 +### 关于字母大小写 尽管本文中的大小写都用,但实际你喜欢用哪一种就用哪一种。所欲哦没有被双引号包围的SIMULA程序都会被转为大写。你甚至可以写BegIN或eNd。 -###基本组成部分 +### 基本组成部分 所以我们必须把代码放在 begin 和 end 里。那么两者之间的文字有什么要求呢? 两种类型结构组成了SIMULA系统,声明和表达式。还有一些SIMULA系统忽略的部分,这些叫注释的部分仅仅是方便人们更容易理解代码。 -###声明 +### 声明 在例1.1里,begin后的第一个指令是声明 @@ -85,7 +85,7 @@ begin和end被称为关键字,因为它们有特殊的用途不能用于做其 很多人都认为这中写法很简洁。这种写法被叫做列表声明,定义了一系列类型相同的标识符。 -###注释 +### 注释 下一行是注释。以关键字 comment 开始,随后是一些文字和分号 @@ -97,7 +97,7 @@ begin和end被称为关键字,因为它们有特殊的用途不能用于做其 当你在写独立部分代码时,不会时不时回头看自己写过的代码。但别的人可能需要修改你写的代码。代码的整体介绍,应该能告诉他们你写的这个组件是做什么的,但代码工作的细节可能并不明显。为了帮助这些人理解你的代码,你应该在代码中添加注释。 -###语句 +### 语句 除了上述内容之外的代码,就是语句了。它们告诉SIMULA系统要做什么。 @@ -111,7 +111,7 @@ begin和end被称为关键字,因为它们有特殊的用途不能用于做其 OutImage导致了刚刚创建的行或‘图像’输出到打印机或终端,并重新开始了一行。你注意到它没有任何参数。只有当语句需要从程序中获得信息执行任务时才需要参数。 -###我们对程序做了什么? +### 我们对程序做了什么? 好了,现在我们有了一个所谓的合法SIMULA程序。不幸的是程序还在纸面上,尽管我们知道程序要如何执行,但SIMULA系统不可能从纸上读取它。我们要怎样让系统执行我们的程序呢? @@ -131,7 +131,7 @@ OutImage导致了刚刚创建的行或‘图像’输出到打印机或终端, 注意:要编译运行你的SIMULA程序,你必须能够访问一个SIMULA系统。如果你的机器上没有,你需要买一个(ORZ),但不是每个系统都能使用的。我知道的可以运行SIMULA的支持系统已经在书后列出(...)。如果你的机器不在列表中,给SIMULA A.S.写信,他们可能帮到你。他们的地址已经列出(RBL)。英国的读者可以和我面基。 -###总结 +### 总结 每章都会以一个简单的总结结束,标明了你应当在本章中学到的内容。 @@ -145,7 +145,7 @@ OutImage导致了刚刚创建的行或‘图像’输出到打印机或终端, {{ book.Chapter2 }} -###练习 +### 练习 当我开始学习编程的时候,被告知了最重要的规则,“不动手学不好编程”。最简单的练习也长长能够教一个有经验的程序员一些新的东西。要避免由于有些内容依赖于下一章而错过本章的练习。这一章已经介绍了很多知识点。你可能感觉完全晕菜。不要绝望。通过在后续的章节和练习中使用这些知识,你会很快熟悉他们。我们从三个基本而重要的练习开始。