АЛГОЛ 68


Из Википедии, бесплатной энциклопедии
  (Перенаправлено с АЛГОЛ-68 )
Перейти к навигации Перейти к поиску

АЛГОЛ 68 (сокращение от « Алгоритмический язык 1968» ) - это императивный язык программирования, который был задуман как преемник языка программирования АЛГОЛ 60 , разработанный с целью расширения области применения и более строго определенного синтаксиса и семантики.

Сложность определения языка, состоящего из нескольких сотен страниц, заполненных нестандартной терминологией, затрудняла реализацию компилятора, и было сказано, что у него «нет реализаций и нет пользователей». Это было правдой лишь отчасти; Алгол 68 действительно нашел применение на нескольких нишевых рынках, особенно в Соединенном Королевстве, где он был популярен на машинах International Computers Limited (ICL) и в качестве преподавателя. Вне этих полей использование было относительно ограниченным.

Тем не менее, вклад Алгола 68 в область информатики был глубоким, разносторонним и устойчивым, хотя многие из этих вкладов были публично определены только тогда, когда они вновь появились в впоследствии разработанных языках программирования. Многие языки были разработаны специально в ответ на кажущуюся сложность языка, наиболее заметным из которых был Паскаль , или были повторными реализациями для определенных ролей, например Ада .

Многие языки 1970-х годов прослеживают свой дизайн именно на АЛГОЛе 68, выбирая одни функции и отказываясь от других, которые считались слишком сложными или выходящими за рамки данных ролей. Среди них - язык C , на который непосредственно повлиял АЛГОЛ 68, особенно его строгая типизация и структуры. Большинство современных языков прослеживают, по крайней мере, часть своего синтаксиса либо до C, либо от Pascal, и, таким образом, прямо или косвенно от ALGOL 68.

Обзор

Функции ALGOL 68 включают синтаксис на основе выражений, объявленные пользователем типы и структуры / помеченные объединения, эталонную модель переменных и ссылочных параметров, нарезку строк, массивов и матриц, а также параллелизм.

Алгол 68 был разработан Рабочей группой 2.1 Международной федерации обработки информации (IFIP) IFIP по алгоритмическим языкам и исчислениям. 20 декабря 1968 года язык был официально принят группой, а затем одобрен для публикации Генеральной ассамблеей IFIP.

Алгол 68 был определен с использованием формализма , двухуровневой формальной грамматики , изобретенной Адрианом ван Вейнгаарденом . Грамматики Ван Вейнгаардена используют контекстно-свободную грамматику для создания бесконечного набора продуктов, которые распознают конкретную программу на АЛГОЛе 68; в частности, они способны выразить такие требования , которые во многих других языках программирования технических стандарты помечены семантика , и должны быть выражены в неоднозначности склонной естественного языка прозы, а затем реализованы в компиляторах специального кода , прикрепленный к формальному синтаксическому анализатору языка .

АЛГОЛ 68 был первым (и, возможно, одним из последних) основным языком, для которого было дано полное формальное определение до его реализации.

ЦДХ Костер [8]

Основные цели и принципы построения АЛГОЛА 68:

  1. Полнота и ясность описания [9]
  2. Ортогональность дизайна [10]
  3. Безопасность [11]
  4. Эффективность: [12]
    • Проверка статического режима
    • Анализ, независимый от режима
    • Самостоятельная компиляция
    • Оптимизация цикла
    • Представления - в минимальных и больших наборах символов

Алгол 68 подвергался критике, особенно со стороны некоторых членов его проектного комитета, таких как Кар Хоар и Эдсгер Дейкстра , за отказ от простоты АЛГОЛА 60 , за то, что он стал средством для сложных или слишком общих идей и мало что сделал для решения задачи автора компилятора . проще, в отличие от нарочито простых современников (и конкурентов), таких как C , S-algol и Pascal .

В 1970 году ALGOL 68-R стал первым работающим компилятором для ALGOL 68.

В редакции 1973 г. некоторые особенности, такие как процедуры , гоммы [13] и формальные границы, были опущены. [14] Cf Язык неотредактированного отчета. r0

Хотя европейские оборонные агентства (в Великобритании Royal Signals and Radar Establishment (RSRE)) продвигали использование Алгола 68 для достижения ожидаемых преимуществ безопасности, американская сторона альянса НАТО решила разработать другой проект, язык Ada , сделав его использование обязательным. для оборонных контрактов США.

Алгол 68 также имел заметное влияние в Советском Союзе , детали которого можно найти в статье Андрея Ершова 2014 года: «Алгол 68 и его влияние на программирование в СССР и России», [15] и «Алгол 68 и его влияние. на программирование в СССР и России ". [16]

Стив Борн , входивший в комитет по пересмотру ALGOL 68, перенес некоторые из его идей в свою оболочку Bourne (и, таким образом, в потомки оболочек Unix, такие как Bash ) и в C (и, следовательно, в потомков, таких как C ++ ).

Полную историю проекта можно найти в книге CH Lindsey 's A History of ALGOL 68 . [17] [18]

Полное описание языка см. В «Programming ALGOL 68 Made Easy» [19] доктора Сиан Маунтбэттен или в «Learning ALGOL 68 Genie» [20] Marcel van der Veer, который включает пересмотренный отчет.

История

Происхождение

АЛГОЛ 68, как следует из названия, является продолжением языка АЛГОЛ, который был впервые формализован в 1960 году. В том же году Международная федерация обработки информации (IFIP) сформировала и учредила Рабочую группу по АЛГОЛу, или WG2.1. Эта группа выпустила обновленную спецификацию Алгола 60 в Риме в апреле 1962 года. На последующем собрании в марте 1964 года было решено, что группа должна начать работу над двумя последующими стандартами, Алголом X, который станет новым определением языка. с некоторыми дополнениями и АЛГОЛ Y , который будет иметь возможность изменять свои собственные программы в стиле языка LISP . [21]

Процесс определения

Первое собрание группы ALGOL X состоялось в Принстонском университете в мае 1965 года. В отчете о встрече были отмечены две широко поддерживаемые темы: введение строгой типизации и интерес к концепциям Эйлера « деревьев» или «списков» для работы с коллекциями. [22]

На второй встрече в октябре во Франции были представлены три официальных предложения : ALGOL W Никлауса Вирта вместе с комментариями CAR (Тони) Хоара по поводу структур записи , аналогичным языком Герхарда Зигмюллера и доклад Адриана ван Вейнгардена о том, « Ортогональный дизайн и описание формального языка ». Последнее, написанное почти неразборчивой «W-грамматикой», оказалось решающим сдвигом в эволюции языка. Встреча завершилась соглашением о том, что ван Вейнгаарден переписывает представление Вирта / Хора, используя свою W-грамматику. [22]

Эта, казалось бы, простая задача в конечном итоге оказалась более сложной, чем ожидалось, и повторную встречу пришлось отложить на шесть месяцев. Когда он собрался в апреле 1966 года в Кутвейке , черновик ван Вейнгаардена оставался неполным, и Вирт и Хоар представили версию, использующую более традиционные описания. По общему мнению, их статья была «правильным языком в неправильном формализме». [23] По мере изучения этих подходов стало ясно, что существует разница в способах описания параметров, которые могут иметь реальный эффект, и, хотя Вирт и Хоар протестовали против того, что дальнейшие задержки могут стать бесконечными, комитет решил дождаться фургона. Версия Вейнгаардена. Затем Вирт реализовал свое текущее определение как АЛГОЛ W. [24]

На следующей встрече в Варшаве в октябре 1966 г. [25] был представлен первоначальный отчет Подкомитета ввода-вывода, который собрался в Национальной лаборатории Окриджа и в Университете Иллинойса, но пока не добился большого прогресса. Два предложения с предыдущей встречи были снова рассмотрены, и на этот раз возникла новая дискуссия об использовании указателей ; Алгол W использовал их только для ссылки на записи, в то время как версия ван Вийнгаардена могла указывать на любой объект. Чтобы добавить путаницы, Джон Маккарти представил новое предложение по перегрузке операторов и возможности связывать вместе и / или конструкции, а Клаус Самельсонхотел разрешить анонимные функции . В результате возникла путаница, и возникла дискуссия об отказе от всей работы. [24] Путаница продолжалась во время того, что должно было быть встречей ALGOL Y в Зандворте в мае 1967 года. [22]

Публикация

Черновой вариант отчета был наконец опубликован в феврале 1968 года. Он был встречен «шоком, ужасом и несогласием» [22], в основном из-за сотен страниц нечитаемой грамматики и странной терминологии. Чарльз Х. Линдси попытался выяснить, какой «язык спрятан внутри него» [26], процесс, который потребовал шести человеко-недель усилий. Получившаяся в результате статья «Алгол 68 с меньшим количеством слез» получила широкое распространение. На более широкой встрече по обработке информации в Цюрихе в мае 1968 года участники жаловались, что им навязывают язык и что IFIP был «истинным злодеем этой необоснованной ситуации», поскольку встречи были в основном закрытыми и не было формального механизма обратной связи. Вирт и Петр Наурформально отказались от своих авторских позиций в WG2.1 в то время. [26]

Следующее собрание WG2.1 состоялось в июне 1968 года в Тиррении . Предполагалось, что оно обсудит выпуск компиляторов и другие вопросы, но вместо этого перешло к обсуждению языка. Ван Вейнгаарден ответил, сказав (или пригрозив), что выпустит только еще одну версию отчета. К этому моменту Наур, Хоар и Вирт оставили усилия, и еще несколько угрожали сделать это. [27] Последовало еще несколько встреч, Северный Бервик в августе 1968 года, Мюнхен в декабре, на которых был выпущен официальный отчет в январе 1969 года, но также закончился составлением спорного отчета меньшинства. Наконец, в Банфе, Альбертав сентябре 1969 года проект в целом считался завершенным, и обсуждение главным образом касалось исправлений и значительно расширенного «Введения к отчету». [28]

Эта работа заняла пять лет, сожгла многие величайшие имена в области компьютерных наук и несколько раз зашла в тупик по вопросам как в определении, так и в группе в целом. Почти сразу Хоар выпустил «Критику Алгола 68» [29], на которую широко ссылаются во многих работах. Вирт продолжил развитие концепции ALGOL W и в 1970 году выпустил его как Pascal.

Реализации

АЛГОЛ 68-R

Первая реализация стандарта, основанная на проекте отчета конца 1968 года, была представлена Королевским радарным учреждением в Великобритании как ALGOL 68-R в июле 1970 года. Однако это была часть полного языка, и Барри Майлу , последний редактор Доклада, пошутил: «Это вопрос морали. У нас есть Библия, а вы грешите!» [30] Эта версия, тем не менее, стала очень популярной на машинах ICL и стала широко используемым языком в военном кодировании, особенно в Великобритании. [31]

Среди изменений в 68-R было требование, чтобы все переменные были объявлены перед их первым использованием. Это имело существенное преимущество, так как позволяло компилятору быть однопроходным, поскольку пространство для переменных в записи активации было отложено до того, как оно было использовано. Однако это изменение также имело побочный эффект, состоящий в том, что процессы требовалось дважды объявлять: один раз как объявление типов, а затем снова как тело кода. Другое изменение состояло в том, чтобы исключить предполагаемый режим void , выражение, которое не возвращает значения (названное оператором на других языках) и требующее добавления слова void там, где оно предполагалось. Кроме того, 68-R устранил явную параллельную обработкукоманды на основе пар . [30]

Другие

Первая полная реализация языка была представлена ​​в 1974 году CDC в Нидерландах для серии мэйнфреймов Control Data . Это имело ограниченное использование, в основном преподавание в Германии и Нидерландах. [31]

Версия, похожая на 68-R, была представлена ​​из Университета Карнеги-Меллона в 1976 году как 68S и снова была однопроходным компилятором, основанным на различных упрощениях оригинала и предназначенным для использования на меньших машинах, таких как DEC PDP-11 . Его тоже использовали в основном в учебных целях. [31]

Версия для мэйнфреймов IBM не была доступна до 1978 года, когда она была выпущена в Кембриджском университете . Это было «почти завершено». Линдси выпустила версию для небольших машин, включая IBM PC в 1984 году [31].

Известны три реализации Algol 68 с открытым исходным кодом: [32]

  • a68g , GPLv3 , автор - Марсель ван дер Вир.
  • algol68toc , программный порт с открытым исходным кодом для ALGOL 68RS .
  • экспериментальный интерфейс Algol68 для GCC, написанный Jose E. Marchesi. [33]

Лента новостей

  • "Краткая история Алгола 68"
  • АЛГОЛ 68 - АЛГОЛ 3-го поколения

Алгоритмический язык ALGOL 68 Отчеты и члены рабочих групп

  • Март 1968: Проект отчета по алгоритмическому языку ALGOL 68 [39] - Под редакцией: Адриан ван Вейнгаарден , Барри Дж. Майлу , Джон Пек и Корнелис Х.А. Костер .

«Ван Вейнгаарден однажды охарактеризовал четырех авторов, несколько иронично, как: Костер: транспуттер , Пек: синтаксис, Майлу: исполнитель, Ван Вейнгаарден: партийный идеолог». - Костер.

  • Октябрь 1968 г .: Предпоследний проект отчета по алгоритмическому языку АЛГОЛ 68 - Главы 1–9 [40] Главы 10–12 [41] - Под редакцией: А. ван Вейнгаарден, Б. Дж. Майлу, Дж. Эл Пек и Ч. А. Костер.
  • Декабрь 1968: Отчет об алгоритмическом языке ALGOL 68 - Offprint из Numerische Mathematik, 14, 79-218 (1969); Springer-Verlag. [42] - Под редакцией: А. ван Вейнгаарден, Б. Дж. Майлу, Дж. Э. Пек и Ч. А. Костер.
  • Отчет меньшинства, Алгол Бюллетень AB31.1.1 - подписали: март 1970 Эдсгер Дейкстры , Фрейзер Дункан , Ян Garwick , Тони Хоара , Брайан Рэнделл , Герхард Seegmüller , Wlad Турский , и Майк Вуджер .
  • Сентябрь 1973: Пересмотренный отчет по алгоритмическому языку Algol 68 - Springer-Verlag 1976 [43] - Под редакцией: A. van Wijngaarden, B. Mailloux, J. Peck, K. Koster, M. Sintzoff, CH Lindsey, Lambert Meertens and Ричард Г. Фискер .
  • другие члены WG 2.1, активно участвующие в разработке Алгола 68: [18] Фридрих Л. Бауэр • Ганс Бекич • Герхард Гус • Питер Зилахи Ингерман • Питер Ландин • Чарльз Х. Линдси • Джон Маккарти • Джек Мернер • Питер Наур • Манфред Пол • Виллем ван дер Поэль • Дуг Росс • Клаус Самельсон • Мишель Синцов • Никлаус Вирт • Нобуо Йонеда .

Хронология стандартизации

1968: На 20 декабря 1968 года «Заключительный отчет» (MR 101) был принят Рабочей группа, то впоследствии утвержденной Генеральной Ассамблеей ЮНЕСКО «s МФОЙ для публикации. Перевод стандарта был сделан на русский , немецкий , французский и болгарский , а затем на японский и китайский языки . [44] Стандарт был также доступен на шрифте Брайля .

1984: TC97 рассматривал АЛГОЛ 68 для стандартизации как «новый рабочий элемент» TC97 / N1642 [2] [3] [ постоянная мертвая ссылка ] . Западная Германия, Бельгия, Нидерланды, СССР и Чехословакия были готовы участвовать в разработке стандарта, но СССР и Чехословакия «не были подходящими членами правильных комитетов ISO» [4], и стандартизация ISO в Алголе 68 застопорилась. [5]

1988: Впоследствии АЛГОЛ 68 стал одним из стандартов ГОСТ в России.

  • ГОСТ 27974-88 Язык программирования АЛГОЛ 68 - Язык программирования АЛГОЛ 68 [45]
  • ГОСТ 27975-88 Язык программирования АЛГОЛ 68 расширенный - Язык программирования АЛГОЛ 68 расширенный [46]

Известные языковые элементы

Жирные символы и зарезервированные слова

Стандартный язык содержит около шестидесяти зарезервированных слов, обычно выделенных жирным шрифтом, а некоторые из них имеют эквиваленты «кратких символов»:

режим , op , prio , proc , flex , heap , loc , long , ref , short , bits , bool , bytes , char , comp , int , real , sema , string , void , channel , file , format , struct , union , в "@",либо r0 , равно ": =:", isnt is not  is not r0 ": / =:" ": ≠:", из "→" r0 , true , false , empty , nil "○", пропустить "~", co " ¢ ", комментарий " ¢ ", pr , pragmat , case ~ in ~ ouse ~ in ~ out ~ esac " (~ | ~ |: ~ | ~ | ~) ",для ~ от ~ до ~by ~ while ~ do ~ od , if ~ then ~ elif ~ then ~ else ~ fi "(~ | ~ |: ~ | ~ | ~)", par  begin ~ end "(~)", перейти к , перейти , выйти "." r0 .

Единицы: выражения

Базовая языковая конструкция - это единица . Единицей может быть формула , заключенное предложение , обычный текст или одна из нескольких технически необходимых конструкций (присваивание, переход, пропуск, nihil). Термин техническая заключенной оговорка унифицирует некоторые из неотъемлемо Брекетинга конструкций , известных как блок , сделать заявление , переключатель заявление в других современных языках. Когда используются ключевые слова, обычно обратная последовательность символов вводящего ключевого слова используется для завершения вложения, например ( if ~ then ~ else ~ fi , case\ В \ из \ ESAC , для \ в то время как \ делать \ оды ). Этот синтаксис защищенной команды был повторно использован Стивеном Борном в общей оболочке Unix Bourne . Выражение также может давать множественное значение , которое создается из других значений дополнительным условием . Эта конструкция выглядит как пакет параметров вызова процедуры.

режим: Объявления

Основные типы данных ( так называемые modeы в Алгол 68 жаргоне) являются real, int, compl( комплексное число ), bool, char, bitsи bytes. Например:

int n = 2; co n фиксируется как константа 2. co int m: = 3; co m - это вновь созданная локальная переменная , значение которой изначально установлено на 3. co co Это сокращение от ref int m = loc int: = 3; co real avogadro = 6,0221415⏨23; co Число Авогадро co long long real long long long pi = 3,14159 26535 89793 23846 26433 83279 50288 41971 69399 37510; полный квадратный корень из минус единицы = 0 1;

Однако объявление real x;- всего лишь синтаксический сахар для . То есть на самом деле это постоянный идентификатор для ссылки на вновь созданную локальную действительную переменную.ref real x = loc real;x

Кроме того, вместо того, чтобы определять floatи double, или, intи longи shortт. Д., АЛГОЛ 68 предоставляет модификаторы , так что, например, текущее общее doubleбудет записано как long real или long long real , например. Константы prelude max real и min long intпредназначены для адаптации программ к различным реализациям.

Все переменные должны быть объявлены, но объявление не должно предшествовать первому использованию.

примитив-декларатор: int , реальный , компл , комплексный G , bool , char , строка , биты , байты , формат , файл , канал G , канал , сема

  • биты - "упакованный вектор" типа bool .
  • bytes - «упакованный вектор» char .
  • string - гибкий массив символов .
  • Сема - это сема phore , который может быть инициализирован с оп Erator уровня .

Сложные типы можно создавать из более простых с помощью различных конструкторов типов:

  • ref mode - ссылка на значение типа mode , аналогично & в C / C ++ и ref в Pascal
  • struct - используется для построения структур, таких как struct в C / C ++ и запись в Pascal
  • union - используется для создания объединений, как в C / C ++ и Pascal
  • proc - используется для указания процедур, таких как функции в C / C ++ и процедуры / функции в Pascal

Для некоторых примеров см. Сравнение АЛГОЛА 68 и C ++ .

Другие символы объявления включают: flex , heap , loc , ref , long , short , event S

  • flex - объявить массив гибким, т.е. он может увеличиваться в длину по запросу.
  • куча - выделить переменной немного свободного места из глобальной кучи.
  • loc - выделить переменной немного свободного места в локальном стеке.
  • долго - объявить Int , реальное или компл быть из длинного размера эр.
  • Короче говоря - провозгласить ИНТ , реальным или компл быть из короткого размера эр.

Имя для режима (типа) может быть объявлено с помощью объявления режима , которое похоже на typedef в C / C ++ и набирает в Pascal:

 int max = 99; режим newmode = [0: 9] [0: max] struct ( long  real a, b, c, short  int i, j, k, ref  real r );

Это похоже на следующий код C:

 const int max = 99 ;   typedef struct {   двойной a , b , c ; короткие i , j , k ; float * r ;          } новый режим [ 9 + 1 ] [ макс + 1 ]; 

Для АЛГОЛА 68 слева от символа равенства появляется только указание режима нового режима, и, в первую очередь, конструкция выполняется и может быть прочитана слева направо без учета приоритетов. Кроме того, нижняя граница массивов Algol 68 по умолчанию равна единице, но может быть любым целым числом от - max int до max int .

Объявления режима позволяют типам быть рекурсивными : определяться прямо или косвенно в терминах самих себя. Это связано с некоторыми ограничениями - например, эти объявления являются незаконными:

 режим A = ref A режим A = структура (A a, B b) режим A = proc (A a) A

пока они действительны:

 mode A = struct ( ref A a, B b) mode A = proc ( ref A a) ref A

Принуждение: кастинг

В Приведении производит coercee из coercend по три критериям: априорный режим coercend перед нанесением какого - либо принуждения, апостериорная режим coercee требуемой после тех принуждений и синтаксической позиции или «сорта» в coercee . Принуждение может быть каскадным.

Шесть возможных принуждения называются депроцедурацией , разыменованием , объединением , расширением , греблей и опорожнением . Каждое принуждение, кроме объединения , предписывает соответствующее динамическое воздействие на связанные значения. Следовательно, многие примитивные действия могут быть запрограммированы неявно с помощью принуждения.

Сила контекста - разрешенные принуждения:

  • мягкий - депроцедура
  • weak - разыменование или депроцедура, приводящая к имени
  • кроткий - разыменование или депроцедура
  • твердый - кроткий, затем объединяющий
  • сильный - твердый, за которым следует расширение, гребля или мочеиспускание

Иерархия принуждения с примерами

АЛГОЛ 68 имеет иерархию контекстов, которые определяют виды принуждения, доступные в определенной точке программы. Эти контексты:

Дополнительные сведения о первичных, вторичных, третичных и четвертичных компонентах см. В разделе «Приоритет операторов» .

pr & co: Прагматики и комментарии

Pragmats - это директивы в программе, обычно указывающие компилятору; в новых языках это называется «прагмами» (нет). например

pragmat heap = 32 pragmat pr heap = 32 pr

Комментарии можно вставлять разными способами:

¢ Оригинальный способ добавления ваших 2 цента к программе ¢ комментарий «жирный» комментарий комментарий co Стиль я комментарий co# Стиль ii комментарий #
£ Это комментарий хеша / фунта для британской клавиатуры £

Обычно комментарии не могут быть вложены в АЛГОЛ 68. Это ограничение можно обойти, используя различные разделители комментариев (например, использовать хэш только для временного удаления кода).

Выражения и составные утверждения

Алгол 68, будучи языком программирования, ориентированным на выражения , значение, возвращаемое оператором присваивания, является ссылкой на место назначения. Таким образом, действует следующий код АЛГОЛА 68:

 реальная половина пи, один пи; один пи: = 2 * (половина пи: = 2 * дуга загар (1))

Это понятие присутствует , среди прочего, в C и Perl . Обратите внимание, что, как и в более ранних языках, таких как Algol 60 и FORTRAN , в идентификаторах разрешены пробелы, так что half piэто единственный идентификатор (что позволяет избежать подчеркивания по сравнению с верблюжьим регистром по сравнению со всеми проблемами нижнего регистра ).

В качестве другого примера, чтобы выразить математическое представление о сумме от f(i)от I = 1 до п, следующий Алгол 68 Целого выражение хватает:

( int sum: = 0; от i до n сделать sum +: = f (i) od ; sum)

Обратите внимание, что, будучи целочисленным выражением, предыдущий блок кода может использоваться в любом контексте, где может использоваться целочисленное значение . Блок кода возвращает значение последнего вычисленного выражения; эта идея присутствует в Лиспе среди других языков.

Все составные операторы оканчиваются характерными закрывающими скобками:

  • если условия выбора:
 if условие then операторы [ else операторы] fi «краткая» форма: (условие | утверждения | утверждения)
 если Condition1 затем ОТЧЕТНОСТЬ Элифа condition2 затем заявление [ остальное заявления] фи «краткая» форма: (условие1 | операторы |: условие2 | операторы | операторы)

Эта схема не только позволяет избежать проблемы зависания else, но также позволяет избежать использования beginи endво встроенных последовательностях операторов .

  • условия выбора случая :
 case switch in операторы, операторы, ... [ операторы out ] esac «краткая» форма: (переключатель | операторы, операторы, ... | операторы)
 case switch1 в операторах, операторах, ... ouse switch2 в операторах, операторах, ... [ операторы out ] esac "краткая" форма оператора case : (switch1 | операторы, операторы, ... |: switch2 | операторы, операторы , ... | заявления)

Пример предложения выбора с краткими символами:

дни процесса в месяце = ( int год, месяц) int : (месяц | 31, (год ÷ × 4 = 0 ∧ год ÷ × 100 ≠ 0 ∨ год ÷ × 400 = 0 | 29 | 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );

Пример предложения выбора с полужирным шрифтом :

дни процесса в месяце = ( int год, месяц) int : case месяц в 31, если год кратен 4 э 0 и год кратен 100 п 0 или год кратен 400 эк 0 тогда 29 еще 28 ц , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 esac ;

Пример предложения выбора, в котором используются жирный и краткий символы:

дни процесса в месяце = ( int год, месяц) int : case месяц в¢ янв. ¢ 31,
¢ ¢ февраль (год моды 4 = 0 и года кратен 100 ≠ 0 или год кратен 400 = 0 | 29 | 28)
¢ марта ¢ 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ¢ до декабря ¢ esac ;

В Algol68 переключатель может быть либо типа int, либо (однозначно) union . Последний позволяет применять строгую типизацию к переменным объединения . cf union ниже, например.

  • предложение цикла do :
[ для индекса] [ от первого] ​​[ по приращению] [ до последнего] [в то время как условие] операторы do od Минимальная форма «предложения цикла» такова: операторы do od

Это считается «универсальным» циклом, полный синтаксис:

для i от 1 до -22 до -333, а i × i ≠ 4444 do ~ od

У конструкции есть несколько необычных аспектов:

  • только сделать \ од часть является обязательной, и в этом случае цикл будет повторять до бесконечности.
  • таким образом, положение на 100 у ~ О.Д. , будет перебирать только 100 раз.
  • в то время как «синтаксический элемент» позволил программисту отдохнуть от за петлю рано. например
int сумма sq: = 0;для меня пока print (("Пока:", i, новая строка)); сумма sq ≠ 70 ↑ 2делать сумма sq +: = i ↑ 2od

Последующие «расширения» к стандартному Algol68 позволили к синтаксическому элементу должны быть заменены UPTO и Downto для достижения небольшой оптимизации. В те же компиляторы также включены:

  • до (C) - для позднего завершения цикла.
  • foreach (S) - для параллельной работы с массивами .

Дополнительные примеры можно найти в примерах кода ниже.

struct, union & [:]: структуры, объединения и массивы

Алгол 68 поддерживает массивы с любым количеством измерений и позволяет нарезать целые или частичные строки или столбцы.

  вектор моды = [1: 3] действительный ; # объявление векторного режима (typedef) #  mode  matrix = [1: 3,1: 3] real ; # объявление режима матрицы (typedef) #  вектор v1: = (1,2,3); # исходная переменная массива (1,2,3) # [] real v2 = (4,5,6); # Константа массив, тип эквивалентен вектор , оценки являются подразумеваемой #  оп + = ( вектор а, б) вектор : # двоичного оп Erator определения # ( векториз; для i от ⌊a до ⌈a do out [i]: = a [i] + b [i] od ; из); матрица m: = (v1, v2, v1 + v2); печать ((м [, 2:])); # срез 2-го и 3-го столбцов #

Матрицы можно разрезать любым способом, например:

 ref  вектор row = m [2,]; # определить ссылку (указатель) на вторую строку #  вектор ссылки col = m [, 2]; # определить ссылку (указатель) на 2-й столбец #

АЛГОЛ 68 поддерживает множественные полевые структуры ( структуры ) и объединенные режимы . Ссылочные переменные могут указывать на любой режим, включая срезы массива и поля структуры.

В качестве примера всего этого приведем традиционное объявление связанного списка:

 режим  node = union ( void , real , int , comp , string ), list = struct ( node val, ref  list next);

Пример использования для накидной случае из узла :

proc: процедуры

Объявления процедур ( proc ) требуют спецификации типа как для параметров, так и для результата ( недействительно, если нет):

 proc max of real = ( real a, b) real : если a> b, то a else b fi ;

или, используя «краткую» форму условного оператора:

 proc max of real = ( real a, b) real : (a> b | a | b); (а> б | а | б);

Возвращаемое значение a proc- это значение последнего выражения, вычисленного в процедуре. Ссылки на процедуры ( ref proc ) также разрешены. Параметры вызова по ссылке предоставляются путем указания ссылок (например, ref real) в формальном списке аргументов. В следующем примере определяется процедура, которая применяет функцию (указанную в качестве параметра) к каждому элементу массива:

 proc apply = ( ref [] real a, proc ( real ) real f):   для i от  lwb a до  upb a do a [i]: = f (a [i]) od

Такая простота кода была недостижима в предшественнике ALGOL 68, ALGOL 60 .

op: Операторы

Программист может определять новые операторы, и как те, так и предопределенные операторы могут быть перегружены, а их приоритеты могут быть изменены кодером. В следующем примере оператор определяется maxкак с диадической, так и с монадической версиями (сканирование элементов массива).

 prio  max = 9;   op  max = ( int a, b) int : (a> b | a | b); op  max = ( real a, b) real : (a> b | a | b); op  max = ( comp a, b) comp : ( abs a> abs b | a | b);   op  max = ([] real a) real : ( real out: = a [ lwb a]; для i от  lwb a + 1 до  upb a do (a [i]> out | out: = a [i]) od ; из)

Массив, процедура, разыменование и операции принуждения

Это технически не операторы, а скорее « единицы, связанные с именами ».

Монадические операторы

Диадические операторы с соответствующими приоритетами

Specific details:

  • Tertiaries include names nil and ○.
  • lws: In Algol68r0 the operators lws and ⎩ ... both return true if the lower state of the dimension of an array is fixed.
  • The ups and ⎧ operators are similar on the upper state.
  • The lwb and upb operators are automatically available on unions of different orders (and modes) of arrays. eg. upb of union([]int, [,]real, flex[,,,]char)

Assignation and identity relations etc

These are technically not operators, rather they are considered "units associated with names"

Note: Quaternaries include names skip and ~.

":=:" (alternatively "is") tests if two pointers are equal; ":/=:" (alternatively "isnt") tests if they are unequal.

Why :=: and :/=: are needed: Consider trying to compare two pointer values, such as the following variables, declared as pointers-to-integer:

ref int ip, jp

Now consider how to decide whether these two are pointing to the same location, or whether one of them is pointing to nil. The following expression

ip = jp

will dereference both pointers down to values of type int, and compare those, since the "=" operator is defined for int, but not ref int. It is not legal to define "=" for operands of type ref int and int at the same time, because then calls become ambiguous, due to the implicit coercions that can be applied: should the operands be left as ref int and that version of the operator called? Or should they be dereferenced further to int and that version used instead? Therefore the following expression can never be made legal:

ip = nil

Hence the need for separate constructs not subject to the normal coercion rules for operands to operators. But there is a gotcha. The following expressions:

ip :=: jp
ip :=: nil

while legal, will probably not do what might be expected. They will always return false, because they are comparing the actual addresses of the variables ip and jp, rather than what they point to. To achieve the right effect, one would have to write

ip :=: ref int(jp)
ip :=: ref int(nil)

Special characters

IBM 2741 keyboard with APL symbols

Most of Algol's "special" characters (⊂, ≡, ␣, ×, ÷, ≤, ≥, ≠, ¬, ⊃, ≡, ∨, ∧, →, ↓, ↑, ⌊, ⌈, ⎩, ⎧, ⊥, ⏨, ¢, ○ and □) can be found on the IBM 2741 keyboard with the APL "golf-ball" print head inserted; these became available in the mid-1960s while ALGOL 68 was being drafted. These characters are also part of the Unicode standard and most of them are available in several popular fonts.

transput: Input and output

Transput is the term used to refer to ALGOL 68's input and output facilities. It includes pre-defined procedures for unformatted, formatted and binary transput. Files and other transput devices are handled in a consistent and machine-independent manner. The following example prints out some unformatted output to the standard output device:

 print ((newpage, "Title", newline, "Value of i is ", i, "and x[i] is ", x[i], newline))

Note the predefined procedures newpage and newline passed as arguments.

Books, channels and files

The transput is considered to be of books, channels and files:

  • Books are made up of pages, lines and characters, and may be backed up by files.
    • A specific book can be located by name with a call to match.
  • channels correspond to physical devices. e.g. card punches and printers.
    • Three standard channels are distinguished: stand in channel, stand out channel, stand back channel.
  • A file is a means of communicating between a program and a book that has been opened via some channel.
    • The mood of a file may be read, write, char, bin, and opened.
    • transput procedures include: establish, create, open, associate, lock, close, scratch.
    • position enquires: char number, line number, page number.
    • layout routines include:
      • space, backspace, newline, newpage.
      • get good line, get good page, get good book, and proc set=(ref file f, int page,line,char)void:
    • A file has event routines. e.g. on logical file end, on physical file end, on page end, on line end, on format end, on value error, on char error.

formatted transput

"Formatted transput" in ALGOL 68's transput has its own syntax and patterns (functions), with formats embedded between two $ characters.[47]

Examples:

 printf (($2l"The sum is:"x, g(0)$, m + n)); ¢ prints the same as: ¢ print ((new line, new line, "The sum is:", space, whole (m + n, 0))

par: Parallel processing

ALGOL 68 supports programming of parallel processing. Using the keyword par, a collateral clause is converted to a parallel clause, where the synchronisation of actions is controlled using semaphores. In A68G the parallel actions are mapped to threads when available on the hosting operating system. In A68S a different paradigm of parallel processing was implemented (see below).

int initial foot width = 5;mode foot = struct( string name, sema width, bits toe ¢ packed vector of BOOL ¢
);
 foot left foot:= foot("Left", level initial foot width, 2r11111), right foot:= foot("Right", level initial foot width, 2r11111);
 
¢ 10 round clip in a 1968 Colt Python .357 Magnum ¢sema rounds = level 10;
 
¢ the Magnum needs more barrels to take full advantage of parallelism ¢sema acquire target = level 1;
 prio ∧:= = 1;op ∧:= = (ref bits lhs, bits rhs)ref bits: lhs := lhs ∧ rhs;
 proc shoot = (ref foot foot)void: ( ↓acquire target; ↓rounds; print("BANG! "); ↓width → foot; toe → foot ∧:= ¬(bin 1 shl level width → foot); printf(($g": Ouch!! – "5(g)l$, name → foot, []bool(toe → foot)[bits width – initial foot width + 1:])); ↑acquire target
);
 
¢ do shooting in parallel to cater for someone hoping to stand on just one foot ¢par ( for toe to initial foot width do shoot (left foot) od, ¢ <= a comma is required ¢ for toe to initial foot width do shoot(right foot) od)

Examples of use

Code sample

This sample program implements the Sieve of Eratosthenes to find all the prime numbers that are less than 100. nil is the ALGOL 68 analogue of the null pointer in other languages. The notation x of y accesses a member x of a struct y.

begin # Algol-68 prime number sieve, functional style #   proc error = (string s) void: (print(( newline, " error: ", s, newline)); goto stop); proc one to = (int n) list: (proc f = (int m,n) list: (m>n | nil | cons(m, f(m+1,n))); f(1,n));   mode list = ref node; mode node = struct (int h, list t); proc cons = (int n, list l) list: heap node := (n,l); proc hd = (list l) int: ( l is nil | error("hd nil"); skip | h of l ); proc tl = (list l) list: ( l is nil | error("tl nil"); skip | t of l ); proc show = (list l) void: ( l isnt nil | print((" ",whole(hd(l),0))); show(tl(l)));   proc filter = (proc (int) bool p, list l) list: if l is nil then nil elif p(hd(l)) then cons(hd(l), filter(p,tl(l))) else filter(p, tl(l)) fi;   proc sieve = (list l) list: if l is nil then nil else proc not multiple = (int n) bool: n mod hd(l) ≠ 0; cons(hd(l), sieve( filter( not multiple, tl(l) ))) fi;   proc primes = (int n) list: sieve( tl( one to(n) ));   show( primes(100) )end

Operating systems written in ALGOL 68

  • Cambridge CAP computer – All procedures constituting the operating system were written in ALGOL 68C, although several other closely associated protected procedures, such as a paginator, are written in BCPL.[48]
  • Eldon 3 – Developed at Leeds University for the ICL 1900 was written in ALGOL 68-R.[49]
  • Flex machine – The hardware was custom and microprogrammable, with an operating system, (modular) compiler, editor, garbage collector and filing system all written in ALGOL 68RS. The command shell Curt[50] was designed to access typed data similar to Algol-68 modes.
  • VME – S3 was the implementation language of the operating system VME. S3 was based on ALGOL 68 but with data types and operators aligned to those offered by the ICL 2900 Series.

Note: The Soviet Era computers Эльбрус-1 (Elbrus-1) and Эльбрус-2 were created using high-level language Эль-76 (AL-76), rather than the traditional assembly. Эль-76 resembles Algol-68, The main difference is the dynamic binding types in Эль-76 supported at the hardware level. Эль-76 is used for application, job control, system programming.[51]

Applications

Both ALGOL 68C and ALGOL 68-R are written in ALGOL 68, effectively making ALGOL 68 an application of itself. Other applications include:

  • ELLA – a hardware description language and support toolset. Developed by the Royal Signals and Radar Establishment during the 1980s and 1990s.
  • RAF Strike Command System – "... 400K of error-free ALGOL 68-RT code was produced with three man-years of work. ..."[52]

Libraries and APIs

  • NAG Numerical Libraries – a software library of numerical analysis routines. Supplied in ALGOL 68 during the 1980s.
  • TORRIX – a programming system for operations on vectors and matrices over arbitrary fields and of variable size by S. G. van der Meulen and M. Veldhorst.[53]

Program representation

A feature of ALGOL 68, inherited from the ALGOL tradition, is its different representations. There is a representation language used to describe algorithms in printed work, a strict language (rigorously defined in the Report), and an official reference language intended to be used in compiler input. The examples contain bold typeface words, this is the strict language. ALGOL 68's reserved words are effectively in a different namespace from identifiers, and spaces are allowed in identifiers, so this next fragment is legal:

 int a real int = 3 ;

The programmer who writes executable code does not always have an option of bold typeface or underlining in the code as this may depend on hardware and cultural issues. Different methods to denote these identifiers have been devised. This is called a stropping regime. For example, all or some of the following may be available programming representations:

 int a real int = 3; # the strict language #
'INT'A REAL INT = 3; # QUOTE stropping style #
.INT A REAL INT = 3; # POINT stropping style # INT a real int = 3; # UPPER stropping style # int a_real_int = 3; # RES stropping style, there are 61 accepted reserved words #

All implementations must recognize at least POINT, UPPER and RES inside PRAGMAT sections. Of these, POINT and UPPER stropping are quite common, while RES stropping is a contradiction to the specification (as there are no reserved words). QUOTE (single apostrophe quoting) was the original recommendation, while matched apostrophe quoting, common in ALGOL 60, is not used much in ALGOL 68.[54]

The following characters were recommended for portability, and termed "worthy characters" in the Report on the Standard Hardware Representation of Algol 68 Archived 2014-01-02 at the Wayback Machine:

  • ^ Worthy Characters: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "#$%'()*+,-./:;<=>@[ ]_|

This reflected a problem in the 1960s where some hardware didn't support lower-case, nor some other non-ASCII characters, indeed in the 1973 report it was written: "Four worthy characters — "|", "_", "[", and "]" — are often coded differently, even at installations which nominally use the same character set."

  • Base characters: "Worthy characters" are a subset of "base characters".

Example of different program representations

ALGOL 68 allows for every natural language to define its own set of keywords Algol-68. As a result, programmers are able to write programs using keywords from their native language. Below is an example of a simple procedure that calculates "the day following", the code is in two languages: English and German.[citation needed]

 # Next day date - English variant # mode date = struct(int day, string month, int year); proc the day following = (date x) date: if day of x < length of month (month of x, year of x) then (day of x + 1, month of x, year of x) elif month of x = "December" then (1, "January", year of x + 1) else (1, successor of month (month of x), year of x) fi;
 # Nachfolgetag - Deutsche Variante # menge datum = tupel(ganz tag, wort monat, ganz jahr); funktion naechster tag nach = (datum x) datum: wenn tag von x < monatslaenge(monat von x, jahr von x) dann (tag von x + 1, monat von x, jahr von x) wennaber monat von x = "Dezember" dann (1, "Januar", jahr von x + 1) ansonsten (1, nachfolgemonat(monat von x), jahr von x) endewenn;

Russian/Soviet example:In English Algol68's case statement reads case ~ in ~ out ~ esac, in Cyrillic this reads выб ~ в ~ либо ~ быв.

Some Vanitas

For its technical intricacies, ALGOL 68 needs a cornucopia of methods to deny the existence of something:

skip, "~" or "?"C – an undefined value always syntactically valid,empty – the only value admissible to void, needed for selecting void in a union,void – syntactically like a mode, but not one,nil or "○" – a name not denoting anything, of an unspecified reference mode,
() or specifically [1:0]int – a vacuum is an empty array (here specifically of mode []int).undefined – a standards reports procedure raising an exception in the runtime system.
ℵ – Used in the standards report to inhibit introspection of certain types. e.g. sema

c.f. below for other examples of ℵ.

The term nil is var always evaluates to true for any variable (but see above for correct use of is :/=:), whereas it is not known to which value a comparison x < skip evaluates for any integer x.

ALGOL 68 leaves intentionally undefined what happens in case of integer overflow, the integer bit representation, and the degree of numerical accuracy for floating point. In contrast, the language Java has been criticized for over-specifying the latter.

Both official reports included some advanced features that were not part of the standard language. These were indicated with an ℵ and considered effectively private. Examples include "≮" and "≯" for templates, the outtype/intype for crude duck typing, and the straightout and straightin operators for "straightening" nested arrays and structures.

Extract from the 1973 report:

§10.3.2.2. Transput modes
a) modesimplout = union (≮ℒ int≯, ≮ℒ real≯, ≮ℒ compl≯, bool, ≮ℒ bits≯, char, [ ] char);
b) modeouttype = ¢ an actual – declarer specifying a mode united from a sufficient set of modes none of which is 'void' or contains 'flexible', 'reference to', 'procedure' or 'union of' ¢;
c) modesimplin = union (≮ref ℒ int≯, ≮ref ℒ real≯, ≮refcompl≯, ref bool, ≮ref ℒ bits≯, ref char, ref [ ] char, ref string);
d) modeintype = ¢ ... ¢;
 
§10.3.2.3. Straightening
a) opstraightout = (outtype x) [ ] simplout: ¢ the result of "straightening" 'x' ¢;
b) opstraightin = (intype x) [ ] simplin: ¢ the result of straightening 'x' ¢;

Comparisons with other languages

  • 1973 – Comparative Notes on Algol 68 and PL/I – S. H. Valentine – February 1973
  • 1973 – B. R. Alexander and G. E. Hedrick. A Comparison of PL/1 and ALGOL 68. International Symposium on Computers and Chinese Input/Output Systems. pp. 359–368.
  • 1976 – Evaluation of ALGOL 68, JOVIAL J3B, Pascal, Simula 67, and TACPOL Versus TINMAN – Requirements for a Common High Order Programming Language.
  • 1976 – A Language Comparison[permanent dead link] – A Comparison of the Properties of the Programming Languages ALGOL 68, CAMAC-IML, Coral 66, PAS 1, PEARL, PL/1, PROCOL, RTL/2 in Relation to Real Time Programming – R. Roessler; K. Schenk – October 1976 [7]
  • 1976 – Evaluation of ALGOL 68, JOVIAL J3B, PASCAL, SIMULA 67, and TACPOL Versus [Steelman language requirements|TINMAN] Requirements for a Common High Order Programming Language. October 1976 [8]
  • 1977 – Report to the High Order-Language Working Group (HOLWG) – Executive Summary – Language Evaluation Coordinating Committee – Evaluation of PL/I, Pascal, ALGOL 68, HAL/S, PEARL, SPL/I, PDL/2, LTR, CS-4, LIS, Euclid, ECL, Moral, RTL/2, Fortran, COBOL, ALGOL 60, TACPOL, CMS-2, Simula 67, JOVIAL J3B, JOVIAL J73 & Coral 66.
  • 1977 – A comparison of PASCAL and ALGOL 68[55] – Andrew S. Tanenbaum – June 1977.
  • 1980 – A Critical Comparison of Several Programming Language Implementations – Algol 60, FORTRAN, Pascal and Algol 68.
  • 1993 – Five Little Languages and How They Grew – BLISS, Pascal, Algol 68, BCPL & C – Dennis M. Ritchie – April 1993.
  • 1999 – On Orthogonality: Algol68, Pascal and C
  • 2000 – A Comparison of Arrays in ALGOL 68 and BLISS – University of Virginia – Michael Walker – Spring 2000
  • 2009 – On Go – oh, go on – How well will Google's Go stand up against Brand X programming language? – David Given – November 2009
  • 2010 – Algol and Pascal from "Concepts in Programming Languages – Block-structured procedural languages" – by Marcelo Fiore
  • Comparison of ALGOL 68 and C++

Revisions

Except where noted (with a superscript), the language described above is that of the "Revised Report(r1)".

The language of the unrevised report

The original language (As per the "Final Report"r0) differs in syntax of the mode cast, and it had the feature of proceduring, i.e. coercing the value of a term into a procedure which evaluates the term. Proceduring would be intended to make evaluations lazy. The most useful application could have been the short-circuited evaluation of boolean operators. In:

op andf = (bool a,proc bool b)bool:(a | b | false);op orf = (bool a,proc bool b)bool:(a | true | b);

b is only evaluated if a is true.

As defined in ALGOL 68, it did not work as expected, for example in the code:

if false andf co proc bool: co ( print ("Should not be executed"); true)then ...

against the programmers naïve expectations the print would be executed as it is only the value of the elaborated enclosed-clause after andf that was procedured. Textual insertion of the commented-out proc bool: makes it work.

Some implementations emulate the expected behaviour for this special case by extension of the language.

Before revision, the programmer could decide to have the arguments of a procedure evaluated serially instead of collaterally by using semicolons instead of commas (gommas).

For example in:

proc test = (real a; real b) :...
...
test (x plus 1, x);

The first argument to test is guaranteed to be evaluated before the second, but in the usual:

proc test = (real a, b) :...
...
test (x plus 1, x);

then the compiler could evaluate the arguments in whatever order it felt like.

Extension proposals from IFIP WG 2.1

After the revision of the report, some extensions to the language have been proposed to widen the applicability:

  • partial parametrisation (aka Currying): creation of functions (with fewer parameters) by specification of some, but not all parameters for a call, e.g. a function logarithm of two parameters, base and argument, could be specialised to natural, binary or decadic log,
  • module extension: for support of external linkage, two mechanisms were proposed, bottom-up definition modules, a more powerful version of the facilities from ALGOL 68-R and top-down holes, similar to the ENVIRON and USING clauses from ALGOL 68C[56]
  • mode parameters: for implementation of limited parametrical polymorphism (most operations on data structures like lists, trees or other data containers can be specified without touching the pay load).

So far, only partial parametrisation has been implemented, in Algol 68 Genie.

True ALGOL 68s specification and implementation timeline

The S3 language that was used to write the ICL VME operating system and much other system software on the ICL 2900 Series was a direct derivative of Algol 68. However, it omitted many of the more complex features, and replaced the basic modes with a set of data types that mapped directly to the 2900 Series hardware architecture.

Implementation specific extensions

ALGOL 68R(R) from RRE was the first ALGOL 68 subset implementation, running on the ICL 1900. Based on the original language, the main subset restrictions were definition before use and no parallel processing. This compiler was popular in UK universities in the 1970s, where many computer science students learnt ALGOL 68 as their first programming language; the compiler was renowned for good error messages.

ALGOL 68RS(RS) from RSRE was a portable compiler system written in ALGOL 68RS (bootstrapped from ALGOL 68R), and implemented on a variety of systems including the ICL 2900/Series 39, Multics and DEC VAX/VMS. The language was based on the Revised Report, but with similar subset restrictions to ALGOL 68R. This compiler survives in the form of an Algol68-to-C compiler.

In ALGOL 68S(S) from Carnegie Mellon University the power of parallel processing was improved by adding an orthogonal extension, eventing. Any variable declaration containing keyword event made assignments to this variable eligible for parallel evaluation, i.e. the right hand side was made into a procedure which was moved to one of the processors of the C.mmp multiprocessor system. Accesses to such variables were delayed after termination of the assignment.

Cambridge ALGOL 68C(C) was a portable compiler that implemented a subset of ALGOL 68, restricting operator definitions and omitting garbage collection, flexible rows and formatted transput.

Algol 68 Genie(G) by M. van der Veer is an ALGOL 68 implementation for today's computers and operating systems.

"Despite good intentions, a programmer may violate portability by inadvertently employing a local extension. To guard against this, each implementation should provide a PORTCHECK pragmat option. While this option is in force, the compiler prints a message for each construct that it recognizes as violating some portability constraint."[63]

Quotes

  • ... The scheme of type composition adopted by C owes considerable debt to Algol 68, although it did not, perhaps, emerge in a form that Algol's adherents would approve of. The central notion I captured from Algol was a type structure based on atomic types (including structures), composed into arrays, pointers (references), and functions (procedures). Algol 68's concept of unions and casts also had an influence that appeared later. Dennis Ritchie Apr 1993.[2]
  • ... C does not descend from Algol 68 is true, yet there was influence, much of it so subtle that it is hard to recover even when I think hard. In particular, the union type (a late addition to C) does owe to A68, not in any details, but in the idea of having such a type at all. More deeply, the type structure in general and even, in some strange way, the declaration syntax (the type-constructor part) was inspired by A68. And yes, of course, "long". Dennis Ritchie, 18 June 1988[4]
  • "Congratulations, your Master has done it" – Niklaus Wirth[64]
  • The more I see of it, the more unhappy I become – E. W. Dijkstra, 1968[65]
  • [...] it was said that A68's popularity was inversely proportional to [...] the distance from Amsterdam – Guido van Rossum[66]
  • [...] The best we could do was to send with it a minority report, stating our considered view that, "... as a tool for the reliable creation of sophisticated programs, the language was a failure." [...] – C. A. R. Hoare in his Oct 1980 Turing Award Lecture[67]
  • "[...] More than ever it will be required from an adequate programming tool that it assists, by structure, the programmer in the most difficult aspects of his job, viz. in the reliable creation of sophisticated programs. In this respect we fail to see how the language proposed here is a significant step forward: on the contrary, we feel that its implicit view of the programmer's task is very much the same as, say, ten years ago. This forces upon us the conclusion that, regarded as a programming tool, the language must be regarded as obsolete. [...]" 1968 Working Group minority report on 23 December 1968.[68]

See also

References

Citations

  1. ^ van Wijngaarden, Adriaan; Mailloux, Barry James; Peck, John Edward Lancelot; Koster, Cornelis Hermanus Antonius; Sintzoff, Michel; Lindsey, Charles Hodgson; Meertens, Lambert Guillaume Louis Théodore; Fisker, Richard G., eds. (1976). Revised Report on the Algorithmic Language ALGOL 68 (PDF). Springer-Verlag. ISBN 978-0-387-07592-1. OCLC 1991170. Archived (PDF) from the original on 2019-04-19. Retrieved 2019-05-11.
  2. ^ a b Dennis Ritchie (April 1993). "The Development of the C Language" (PDF). Archived from the original (PDF) on 2005-11-06. Retrieved 2007-04-26.
  3. ^ Influence on C: types, structures, arrays, pointers and procedures – Dennis Ritchie[2]
  4. ^ a b Dennis Ritchie (June 1988). "C and Algol 68". Retrieved 2006-09-15.
  5. ^ Influence on C: union, structure, syntax and long precision – Dennis Ritchie[4]
  6. ^ "A History of C++: 1979−1991" (PDF). March 1993. Page 12, 2nd paragraph: Algol68 [gave] operator overloading(§3.3.3), references (§3.3.4), and the ability to declare variables anywhere in a block (§3.3.1). Retrieved 2008-05-06.
  7. ^ "Interview with Guido van Rossum". July 1998. Archived from the original on 2007-05-01. Retrieved 2007-04-29.
  8. ^ "A Shorter History of ALGOL 68". Archived from the original on 2006-08-10. Retrieved 2006-09-15.
  9. ^ Completeness and clarity of description Archived 2013-03-17 at the Wayback Machine
  10. ^ Orthogonal design Archived 2013-03-17 at the Wayback Machine
  11. ^ Security Archived 2013-03-17 at the Wayback Machine
  12. ^ Efficiency Archived 2013-03-17 at the Wayback Machine
  13. ^ "Gommas?".
  14. ^ Revised Report on the Algorithmic Language Algol 68 Archived 2013-03-17 at the Wayback Machine. jmvdveer.home.xs4all.nl (1968-12-20). Retrieved on 2013-07-21.
  15. ^ Terekhov, Andrey (2014). "ALGOL 68 and Its Impact on the USSR and Russian Programming". 2014 Third International Conference on Computer Technology in Russia and in the Former Soviet Union. pp. 97–106. doi:10.1109/SoRuCom.2014.29. ISBN 978-1-4799-1799-0. S2CID 16097093.
  16. ^ http://toc.proceedings.com/25445webtoc.pdf "Алгол 68 и его влияние на программирование в СССР и России" – pages: 336 & 342
  17. ^ Lindsey 1996.
  18. ^ a b Lindsey, Charles H. (1996). Bergin, T. J.; Gibson, R. G. (eds.). A History of ALGOL 68. ACM SIGPLAN Notices. History of Programming Languages-II. 28. also in ACM SIGPLAN Notices 28(3), March 1993 (includes a comprehensive bibliography of the meetings and discussions before, during and after development of ALGOL 68). ACM Press. pp. 97–132. doi:10.1145/155360.155365. ISBN 978-0-201-89502-5.
  19. ^ Programming Algol 68 Made Easy
  20. ^ Learning ALGOL 68 Genie
  21. ^ Lindsey 1993, p. 7.
  22. ^ a b c d Lindsey 1993, p. 9.
  23. ^ Lindsey 1993, p. 24.
  24. ^ a b Lindsey 1993, p. 10.
  25. ^ "The Algol Bulletin".
  26. ^ a b Lindsey 1993, p. 12.
  27. ^ Lindsey 1993, p. 13.
  28. ^ Lindsey 1993, p. 15.
  29. ^ Hoare, C. a. R. (November 1968). "Critique of ALGOL 68". ALGOL Bulletin. 29: 27–29.
  30. ^ a b Peck, J. E. L., ed. (1970), Proceedings of the IFIP working conference on ALGOL 68 Implementation, Munich: North-Holland, ISBN 0-7204-2045-8
  31. ^ a b c d Koster, C. H. A. "A Shorter History of Algol 68". Archived from the original on 2007-12-17.
  32. ^ van der Veer, Marcel. "Open source Algol 68 implementations". algol68.sourceforge.net.
  33. ^ E. Marchesi, Jose. "Algol68 frontend for GCC". jemarch.net.
  34. ^ Draft Report(DR) Published
  35. ^ Algol 68 Revised Report
  36. ^ Proposals for ALGOL H – A Superlanguage of ALGOL 68
  37. ^ Algol68 S(S) published on the internet
  38. ^ Algol 68 Genie(G)
  39. ^ "Draft Report on the Algorithmic Language ALGOL 68". March 1968. Archived from the original on 2007-09-30. Retrieved 2007-06-22.
  40. ^ "Penultimate Draft Report on the Algorithmic Language ALGOL 68 – Chapters 1-9" (PDF). October 1968. Retrieved 2007-06-22.[permanent dead link]
  41. ^ "Penultimate Draft Report on the Algorithmic Language ALGOL 68 – Chapters 10-12" (PDF). October 1968. Retrieved 2007-06-22.[permanent dead link]
  42. ^ "Report on the Algorithmic Language ALGOL 68" (PDF). December 1968. Retrieved 2007-12-30.
  43. ^ "Revised Report on the Algorithmic Language Algol 68". September 1973. Archived from the original on 2007-09-27. Retrieved 2007-04-30.
  44. ^ Lu Hu-quan (1971). "The Translation of Algol 68 into Chinese" (PDF). Peking, China: Institute of Mathematics, Academia Sinica. Retrieved 2012-08-17.
  45. ^ "GOST 27974-88 Programming language ALGOL 68 – Язык программирования АЛГОЛ 68" (PDF) (in Russian). GOST. 1988. Archived from the original (PDF) on 2008-11-15. Retrieved 2008-11-15.
  46. ^ "GOST 27975-88 Programming language ALGOL 68 extended – Язык программирования АЛГОЛ 68 расширенный" (PDF) (in Russian). GOST. 1988. Archived from the original (PDF) on 2011-04-29. Retrieved 2008-11-15.
  47. ^ Format syntax in ALGOL 68G Archived 2008-01-09 at the Wayback Machine
  48. ^ Needham, R. M.; Wilkes, M. V. (January 1979). "The Cambridge CAP Computer and its Operating System" (PDF). Microsoft Research.
  49. ^ David Holdsworth (Winter 2009–2010). "KDF9 Time Sharing: Eldon 2 is not EGDON!". Computer Resurrection – Number 49. Computer Conservation Society. Retrieved 2010-10-03.
  50. ^ http://www.vitanuova.com/dist/doc/rsre-3522-curt.pdf
  51. ^ Эльбрус Бабаяна и Pentium Пентковского. Ixbt.com. Retrieved on 2013-07-21.
  52. ^ Oliver, J. R.; Newton, R. S. (1979). "Practical experience with ALGOL 68-RT". The Computer Journal. 22 (2): 114–118. doi:10.1093/comjnl/22.2.114.
  53. ^ Applications, libraries, and test suites — Software Preservation Group. Softwarepreservation.org. Retrieved on 2013-07-21.
  54. ^ Revised Report, page 123, footnote
  55. ^ "Vrije Universiteit Amsterdam" (PDF).
  56. ^ Lindsey, C. H.; Boom, H. J. (December 1978). "A Modules and Separate Compilation facility for ALGOL 68". ALGOL Bulletin (43): 19–53. doi:10.1145/1061719.1061724 (inactive 2021-05-31). Retrieved 2020-01-29.CS1 maint: DOI inactive as of May 2021 (link)
  57. ^ "Archived copy" (PDF). Archived from the original (PDF) on 2010-04-15. Retrieved 2010-03-20.CS1 maint: archived copy as title (link)
  58. ^ http://htportal.acm.org/ft_gateway.cfm?id=803425&type=pdf[permanent dead link]
  59. ^ An abstract ALGOL 68 machine and its application in a machine independent compiler – Springer. Springerlink.com. Retrieved on 2013-07-21.
  60. ^ "Archived copy". Archived from the original on 2011-03-10. Retrieved 2010-03-20.CS1 maint: archived copy as title (link)
  61. ^ Open source Algol 68 implementations – Browse Files at. Sourceforge.net. Retrieved on 2013-07-21.
  62. ^ [1] Archived 2006-08-29 at the Wayback Machine
  63. ^ "Archived copy" (PDF). Archived from the original (PDF) on 2014-01-02. Retrieved 2005-08-27.CS1 maint: archived copy as title (link)
  64. ^ C. H. A. Koster (1993). "The Making of Algol 68". CiteSeerX 10.1.1.76.2072. Cite journal requires |journal= (help)
  65. ^ Dijkstra, E. W. "To the Editor ALGOL 68 Mathematische Centrum". Archived from the original on 2007-04-21. Retrieved 2007-04-28.
  66. ^ van Rossum, Guido (June 2005). "Python-Dev Wishlist: dowhile". Retrieved 2007-04-28.
  67. ^ Hoare, C. A. R. (February 1981) [based on his 1980 Turing Award lecture]. "The emperor's old clothes". Communications of the ACM. 24 (2): 75–83. doi:10.1145/358549.358561. S2CID 97895. Archived from the original on 2013-05-08. Alt URL Archived 2017-10-02 at the Wayback Machine
  68. ^ "ALGOL Bulletin (referred to in AB30.1.1.1)". March 1970. Archived from the original on 2007-09-30. Retrieved 2007-03-01.

Works cited

  • Brailsford, D. F. and Walker, A. N., Introductory ALGOL 68 Programming, Ellis Horwood/Wiley, 1979
  • Lindsey, C. H. and van der Meulen, S. G., Informal Introduction to ALGOL 68, North-Holland, 1971
  • Lindsey, C. H. (1993-03-02). "A History of ALGOL 68". ACM SIGPLAN Notices. 28 (3): 97–132. doi:10.1145/155360.155365.
  • McGettrick, A. D., ALGOL 68, A First and Second Course, Cambridge Univ. Press, 1978
  • Peck, J. E. L., An ALGOL 68 Companion, Univ. of British Columbia, October 1971
  • Tanenbaum, A. S., A Tutorial on ALGOL 68, Computing Surveys 8, 155-190, June 1976 and 9, 255-256, September 1977, [9][permanent dead link]
  • Woodward, P. M. and Bond, S. G., ALGOL 68-R Userssic Guide, London, Her Majesty's Stationery Office, 1972

External links

  • Revised Report on the Algorithmic Language ALGOL 68 The official reference for users and implementors of the language (large pdf file, scanned from Algol Bulletin)
  • Revised Report on the Algorithmic Language ALGOL 68 Hyperlinked HTML version of the Revised Report
  • A Tutorial on Algol 68, by Andrew S. Tanenbaum, in Computing Surveys, Vol. 8, No. 2, June 1976, with Corrigenda (Vol. 9, No. 3, September 1977)
  • Algol 68 Genie – a GNU GPL Algol 68 compiler-interpreter
  • Open source ALGOL 68 implementations, on SourceForge
  • Algol68 Standard Hardware representation (.pdf) Archived 2014-01-02 at the Wayback Machine
  • Из истории создания компилятора с Алгол 68
  • Algol 68 – 25 Years in the USSR
  • Система программ динамической поддержки для транслятора с Алгол 68
  • C history with Algol68 heritage
  • McJones, Paul, "Algol 68 implementations and dialects", Software Preservation Group, Computer History Museum, 2011-07-05
  • Web enabled ALGOL 68 compiler for small experiments
Retrieved from "https://en.wikipedia.org/w/index.php?title=ALGOL_68&oldid=1040344638"