Algol (562407), страница 2

Файл №562407 Algol (Несколько текстов для зачёта) 2 страницаAlgol (562407) страница 22015-12-04СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 2)

+ := ARRAY IMPORT RETURN

- ^ BEGIN IN THEN

* = BY IS TO

/ # CASE LOOP TYPE

~ < CLOSE MOD UNTIL

& > CONST MODULE VAR

. <= DIV NIL WHILE

, >= DO OF WITH

; .. ELSE OR

| : ELSIF OUT

$ END POINTER

( ) EXIT PROCEDURE

[ ] FOR RECORD

{ } IF REPEAT

6. Comments may be inserted between any two symbols in a program. They are arbitrary character sequences opened by the bracket (* and closed by *). Comments may be nested. They do not affect the meaning of a program.

4. Declarations and Scope Rules

Every identifier occurring in a program must be introduced by a declaration, unless it is a predeclared identifier. Declarations also specify certain permanent properties of an object, such as whether it is a constant, a type, a variable, or a procedure. The identifier is then used to refer to the associated object.

The scope of an object x extends textually from the point of its declaration to the end of the block (module, procedure, or record) to which the declaration belongs and hence to which the object is local. It excludes the scopes of equally named objects which are declared in nested blocks. The scope rules are:

  1. No identifier may denote more than one object within a given scope (i.e. no identifier may be declared twice in a block);

  2. An object may only be referenced within its scope;

  3. A declaration of a type T containing references to another type T1 may occur at a point where T1 is still unknown. The declaration of T1 must follow in the same block to which T is local;

  4. Identifiers denoting record fields (see 6.3) or methods (see 10.2) are valid in record designators only.

An identifier declared in a module block may be followed by an export mark (" * " or " - ") in its declaration to indicate that it is exported. An identifier x exported by a module M may be used in other modules, if they import M (see Ch.11). The identifier is then denoted as M.x in these modules and is called a qualified identifier. Variables and record fields marked with " - " in their declaration are read-only (variables and fields) or implement-only (methods) in importing modules.

Qualident

=

[ident "."] ident.

IdentDef

=

ident [" * " | " - "].

The following identifiers are predeclared; their meaning is defined in the indicated sections:

ABS (10.3) INTEGER (6.1)

ANYPTR (6.1) FALSE (6.1)

ANYREC (6.1) LEN (10.3)

ASH (10.3) LONG (10.3)

ASSERT (10.3) LONGINT (6.1)

BITS (10.3) MAX (10.3)

BOOLEAN (6.1) MIN (10.3)

BYTE (6.1) NEW (10.3)

CAP (10.3) ODD (10.3)

CHAR (6.1) ORD (10.3)

CHR (10.3) REAL (6.1)

DEC (10.3) SET (6.1)

ENTIER (10.3) SHORT (10.3)

EXCL (10.3) SHORTCHAR (6.1)

HALT (10.3) SHORTINT (6.1)

INC (10.3) SHORTREAL (6.1)

INCL (10.3) SIZE (10.3)

INF (6.1) TRUE (6.1)

5. Constant Declarations

A constant declaration associates an identifier with a constant value.

ConstantDeclaration

=

IdentDef "=" ConstExpression.

ConstExpression

=

Expression.

A constant expression is an expression that can be evaluated by a mere textual scan without actually executing the program. Its operands are constants (Ch.8) or predeclared functions (Ch.10.3) that can be evaluated at compile time. Examples of constant declarations are:

N = 100
limit = 2*N - 1
fullSet = {MIN(SET) .. MAX(SET)}

6. Type Declarations

A data type determines the set of values which variables of that type may assume, and the operators that are applicable. A type declaration associates an identifier with a type. In the case of structured types (arrays and records) it also defines the structure of variables of this type. A structured type cannot contain itself.

TypeDeclaration

=

IdentDef "=" Type.

Type

=

Qualident | ArrayType | RecordType | PointerType | ProcedureType.

Examples:

Table = ARRAY N OF REAL

Tree = POINTER TO Node

Node = EXTENSIBLE RECORD

key: INTEGER;

left, right: Tree

END

CenterTree = POINTER TO CenterNode

CenterNode = RECORD (Node)

width: INTEGER;

subnode: Tree

END

Object = POINTER TO ABSTRACT RECORD END

Function = PROCEDURE (x: INTEGER): INTEGER

6.1 Basic Types

The basic types are denoted by predeclared identifiers. The associated operators are defined in 8.2 and the predeclared function procedures in 10.3. The values of the given basic types are the following:

1. BOOLEAN

the truth values TRUE and FALSE

2. SHORTCHAR

the characters of the Latin1 character set (0X .. 0FFX)

3. CHAR

the characters of the Unicode character set (0X .. 0FFFFX)

4. BYTE

the integers between MIN(BYTE) and MAX(BYTE)

5. SHORTINT

the integers between MIN(SHORTINT) and MAX(SHORTINT)

6. INTEGER

the integers between MIN(INTEGER) and MAX(INTEGER)

7. LONGINT

the integers between MIN(LONGINT) and MAX(LONGINT)

8. SHORTREAL

the real numbers between MIN(SHORTREAL) and MAX(SHORTREAL), the value INF

9. REAL

the real numbers between MIN(REAL) and MAX(REAL), the value INF

10. SET

the sets of integers between 0 and MAX(SET)

Types 4 to 7 are integer types, types 8 and 9 are real types, and together they are called numeric types. They form a hierarchy; the larger type includes (the values of) the smaller type:

REAL >= SHORTREAL >= LONGINT >= INTEGER >= SHORTINT >= BYTE

Types 2 and 3 are character types with the type hierarchy:

CHAR >= SHORTCHAR

6.2 Array Types

An array is a structure consisting of a number of elements which are all of the same type, called the element type. The number of elements of an array is called its length. The elements of the array are designated by indices, which are integers between 0 and the length minus 1.

ArrayType

=

ARRAY [Length {"," Length}] OF Type.

Length

=

ConstExpression.

A type of the form

ARRAY L0, L1, ..., Ln OF T

is understood as an abbreviation of

ARRAY L0 OF

ARRAY L1 OF

...

ARRAY Ln OF T

Arrays declared without length are called open arrays. They are restricted to pointer base types (see 6.4), element types of open array types, and formal parameter types (see 10.1). Examples:

ARRAY 10, N OF INTEGER

ARRAY OF CHAR

6.3 Record Types

A record type is a structure consisting of a fixed number of elements, called fields, with possibly different types. The record type declaration specifies the name and type of each field. The scope of the field identifiers extends from the point of their declaration to the end of the record type, but they are also visible within designators referring to elements of record variables (see 8.1). If a record type is exported, field identifiers that are to be visible outside the declaring module must be marked. They are called public fields; unmarked elements are called private fields.

RecordType

=

RecAttributes RECORD ["("BaseType")"] FieldList {";" FieldList} END.

RecAttributes

=

[ABSTRACT | EXTENSIBLE | LIMITED].

BaseType

=

Qualident.

FieldList

=

[IdentList ":" Type].

IdentList

=

IdentDef {"," IdentDef}.

The usage of a record type is restricted by the presence or absence of one of the following attributes: ABSTRACT, EXTENSIBLE, and LIMITED.

A record type marked as ABSTRACT cannot be instantiated. No variables or fields of such a type can ever exist. Abstract types are only used as base types for other record types (see below).

Variables of a LIMITED record type can only be allocated inside the module where the record type is defined. The restriction applies to static allocation by a variable declaration (Ch. 7) as well as to dynamic allocation by the standard procedure NEW (Ch. 10.3).

Record types marked as ABSTRACT or EXTENSIBLE are extensible, i.e. a record type can be declared as an extension of such a record type. In the example

T0 = EXTENSIBLE RECORD x: INTEGER END

T1 = RECORD (T0) y: REAL END

T1 is a (direct) extension of T0 and T0 is the (direct) base type of T1 (see App. A). An extended type T1 consists of the fields of its base type and of the fields which are declared in T1. All identifiers declared in the extended record must be different from the identifiers declared in its base type record(s). The base type of an abstract record must be abstract.

Alternatively, a pointer type can be specified as the base type. The record base type of the pointer is used as the base type of the declared record in this case.

Each record is implicitly an extension of the predeclared type ANYREC. ANYREC does not contain any fields and can only be used in pointer and variable parameter declarations.

Summary of attributes:

attribute extension allocate

none no yes

EXTENSIBLE yes yes

ABSTRACT yes no

LIMITED in defining module only

Examples of record type declarations:

RECORD

day, month, year: INTEGER

END

LIMITED RECORD

name, firstname: ARRAY 32 OF CHAR;

age: INTEGER;

salary: REAL

END

6.4 Pointer Types

Variables of a pointer type P assume as values pointers to variables of some type T. T is called the pointer base type of P and must be a record or array type. Pointer types adopt the extension relation of their pointer base types: if a type T1 is an extension of T, and P1 is of type POINTER TO T1, then P1 is also an extension of P.

PointerType

=

POINTER TO Type.

If p is a variable of type P = POINTER TO T, a call of the predeclared procedure NEW(p) (see 10.3) allocates a variable of type T in free storage. If T is a record type or an array type with fixed length, the allocation has to be done with NEW(p); if T is an n-dimensional open array type the allocation has to be done with NEW(p, e0, ..., en-1) where T is allocated with lengths given by the expressions e0, ..., en-1. In either case a pointer to the allocated variable is assigned to p. p is of type P. The referenced variable p^ (pronounced as p-referenced) is of type T. Any pointer variable may assume the value NIL, which points to no variable at all.

All fields or elements of a newly allocated record or array are cleared, which implies that all embedded pointers and procedure variables are initialized to NIL.

The predeclared type ANYPTR is defined as POINTER TO ANYREC. Any pointer to a record type is therefore an extension of ANYPTR. The procedure NEW cannot be used for variables of type ANYPTR.

6.5 Procedure Types

Variables of a procedure type T have a procedure (or NIL) as value. If a procedure P is assigned to a variable of type T, the formal parameter lists (see Ch. 10.1) of P and T must match (see App. A). P must not be a predeclared procedure or a method nor may it be local to another procedure.

ProcedureType

=

PROCEDURE [FormalParameters].

6.6 String Types

Values of a string type are sequences of characters terminated by a null character (0X). The length of a string is the number of characters it contains excluding the null character.

Характеристики

Тип файла
Документ
Размер
815,5 Kb
Тип материала
Высшее учебное заведение

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6508
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее