Algol (Несколько текстов для зачёта), страница 5

2015-12-04СтудИзба

Описание файла

Файл "Algol" внутри архива находится в папке "3". Документ из архива "Несколько текстов для зачёта", который расположен в категории "". Всё это находится в предмете "английский язык" из 5 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "остальное", в предмете "английский язык" в общих файлах.

Онлайн просмотр документа "Algol"

Текст 5 страницы из документа "Algol"

Examples of procedure declarations:

PROCEDURE ReadInt (OUT x: INTEGER);

VAR i: INTEGER; ch: CHAR;

BEGIN

i := 0; Read(ch);

WHILE ("0" <= ch) & (ch <= "9") DO

i := 10*i + (ORD(ch)-ORD("0")); Read(ch)

END;

x := i

END ReadInt

 

PROCEDURE WriteInt (x: INTEGER); (*0 <= x <100000*)

VAR i: INTEGER; buf: ARRAY 5 OF INTEGER;

BEGIN

i := 0;

REPEAT buf[i] := x MOD 10;

x := x DIV 10; INC(i)

UNTIL x = 0;

REPEAT DEC(i);

Write(CHR(buf[i] + ORD("0")))

UNTIL i = 0

END WriteInt

 

PROCEDURE WriteString (IN s: ARRAY OF CHAR);

VAR i: INTEGER;

BEGIN

i := 0;

WHILE (i < LEN(s)) & (s[i] # 0X) DO

Write(s[i]); INC(i)

END

END WriteString

 

PROCEDURE log2 (x: INTEGER): INTEGER;

VAR y: INTEGER; (*assume x>0*)

BEGIN

y := 0;

WHILE x > 1 DO x := x DIV 2; INC(y) END;

RETURN y

END log2

 

PROCEDURE Modify (VAR n: Node);

BEGIN

INC(n.key)

END Modify

 

10.2 Methods

Globally declared procedures may be associated with a record type declared in the same module. The procedures are said to be methods bound to the record type. The binding is expressed by the type of the receiver in the heading of a procedure declaration. The receiver may be either a VAR or IN parameter of record type T or a value parameter of type POINTER TO T (where T is a record type). The method is bound to the type T and is considered local to it.

ProcedureHeading

=

PROCEDURE [Receiver] IdentDef [FormalParameters] MethAttributes.

Receiver

=

"(" [VAR | IN] ident ":" ident ")".

MethAttributes

=

["," NEW] ["," (ABSTRACT | EMPTY | EXTENSIBLE)].

If a method M is bound to a type T0, it is implicitly also bound to any type T1 which is an extension of T0. However, if a method M' (with the same name as M) is declared to be bound to T1, this overrides the binding of M to T1. M' is considered a redefinition of M for T1. The formal parameters of M and M' must match, except if M is a function returning a pointer type. In the latter case, the function result type of M' must be an extension of the function result type of M (covariance) (see App. A). If M and T1 are exported (see Chapter 4) M' must be exported too.

The following attributes are used to restrict and document the desired usage of a method: NEW, ABSTRACT, EMPTY, and EXTENSIBLE.

NEW must be used on all newly introduced methods and must not be used on redefining methods. The attribute helps to detect inconsistencies between a record and its extension when one of the two is changed without updating the other.

Abstract and empty method declarations consist of a procedure header only. Abstract methods are never called. A record containing abstract methods must be abstract. A method redefined by an abstract method must be abstract.Calling an empty method has no effect. Empty methods may not return function results and may not have OUT parameters. A record containing new empty methods must be extensible or abstract. A method redefined by an empty method must be empty or abstract. Abstract or empty methods are usually redefined (implemented) in a record extension. They may not be called via super calls. A concrete (nonabstract) record extending an abstract record must implement all abstract methods bound to the base record.

Concrete methods (which contain a procedure body) are either extensible or final (no attribute). A final method cannot be redefined in a record extension. A record containing extensible methods must be extensible or abstract.

If v is a designator and M is a method, then v.M denotes that method M which is bound to the dynamic type of v. Note, that this may be a different method than the one bound to the static type of v. v is passed to M's receiver according to the parameter passing rules specified in Chapter 10.1.

If r is a receiver parameter declared with type T, r.M^ denotes the method M bound to the base type of T (super call). In a forward declaration of a method the receiver parameter must be of the same type as in the actual method declaration. The formal parameter lists of both declarations must match (App. A) and the names of corresponding parameters must be equal.

Methods marked with " - " are "implement-only" exported. Such a method can be redefined in any importing module but can only be called within the module containing the method declaration.

Examples:

PROCEDURE (t: Tree) Insert (node: Tree), NEW, EXTENSIBLE;

VAR p, father: Tree;

BEGIN

p := t;

REPEAT father := p;

IF node.key = p.key THEN RETURN END;

IF node.key < p.key THEN p := p.left ELSE p := p.right END

UNTIL p = NIL;

IF node.key < father.key THEN father.left := node

ELSE father.right := node

END;

node.left := NIL; node.right := NIL

END Insert

 

PROCEDURE (t: CenterTree) Insert (node: Tree); (*redefinition*)

BEGIN

WriteInt(node(CenterTree).width);

t.Insert^ (node) (* calls the Insert method of Tree *)

END Insert

 

PROCEDURE (obj: Object) Draw (w: Window), NEW, ABSTRACT;

 

PROCEDURE (obj: Object) Notify (e: Event), NEW, EMPTY;

 

10.3 Predeclared Procedures

The following table lists the predeclared procedures. Some are generic procedures, i.e. they apply to several types of operands. v stands for a variable, x and y for expressions, and T for a type.

Function procedures

Name

Argument type

Result type

Function

ABS(x)

numeric type

type of x

absolute value

ASH(x, y)

x, y: integer type

INTEGER

arithmetic shift (x * 2^y)

BITS(x)

INTEGER

SET

{i | ODD(x DIV 2^i)}

CAP(x)

character type

type of x

x is a Latin-1 letter: corresponding capital letter

CHR(x)

integer type

CHAR

character with ordinal number x

ENTIER(x)

real type

LONGINT

largest integer not greater than x

LEN(v, x)

v: array; x: integer constant

INTEGER

length of v in dimension x
(first dimension = 0)

LEN(v)

array type

INTEGER

equivalent to LEN(v, 0)

String

INTEGER

length of string (not counting 0X)

LONG(x)

BYTE

SHORTINT

identity

SHORTINT

INTEGER

identity

INTEGER

LONGINT

identity

SHORTREAL

REAL

identity

SHORTCHAR

CHAR

identity

Shortstring

String

identity

MAX(T)

T = basic type

T

maximum value of type T

T = SET

INTEGER

maximum element of a set

MAX(x, y)

integer type

INTEGER

the larger of x and y

real type

REAL

the larger of x and y

MIN(T)

T = basic type

T

minimum value of type T

T = SET

INTEGER

0

MIN(x, y)

integer type

INTEGER

the smaller of x and y

real type

REAL

the smaller of x and y

ODD(x)

integer type

BOOLEAN

x MOD 2 = 1

ORD(x)

CHAR

INTEGER

ordinal number of x

SHORTCHAR

SHORTINT

ordinal number of x

SET

INTEGER

(SUM i: i IN x: 2^i)

SHORT(x)

LONGINT

INTEGER

identity

INTEGER

SHORTINT

identity

SHORTINT

BYTE

identity

REAL

SHORTREAL

identity (truncation possible)

CHAR

SHORTCHAR

projection

String

Shortstring

projection

SIZE(T)

any type

INTEGER

number of bytes required by T

SIZE cannot be used in constant expressions because its value depends on the actual compiler implementation.

 

Proper procedures

Name

Argument types

Function

ASSERT(x)

x: Boolean expression

terminate program execution if not x

ASSERT(x, n)

x: Boolean expression; n: integer constant

terminate program execution if not x

DEC(v)

integer type

v := v - 1

DEC(v, n)

v, n: integer type

v := v - n

EXCL(v, x)

v: SET; x: integer type

v := v - {x}

HALT(n)

integer constant

terminate program execution

INC(v)

integer type

v := v + 1

INC(v, n)

v, n: integer type

v := v + n

INCL(v, x)

v: SET; x: integer type

v := v + {x}

NEW(v)

pointer to record or fixed array

allocate v ^

NEW(v, x0, ..., xn)

v: pointer to open array; xi: integer type

allocate v ^ with lengths x0.. xn

In ASSERT(x, n) and HALT(n), the interpretation of n is left to the underlying system implementation.

 

10.4 Finalization

A predeclared method named FINALIZE is associated with each record type as if it were declared to be bound to the type ANYREC:

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