Парадигмы | Мультипарадигма : параллельная , императивная |
---|---|
Семья | АЛГОЛ |
Разработано | A. van Wijngaarden , BJ Mailloux , JEL Peck и CHA Koster , et al. |
Впервые появился | Заключительный отчет: 1968 г . r0 |
Стабильный выпуск | Algol 68 / RR / Revised Report: 1973 r1 |
Печатная дисциплина | статический , прочный , безопасный , структурный |
Сфера | Лексический |
Основные реализации | |
ALGOL 68C , Algol 68 Genie (недавний), ALGOL 68-R , ALGOL 68RS , ALGOL 68S , FLACC , Алгол 68 Ленинград / Ленинградское отделение , Odra ALGOL 68 | |
Диалекты | |
АЛГОЛ 68 / FR (Заключительный отчет r0 ) | |
Под влиянием | |
АЛГОЛ 60 , АЛГОЛ Y | |
Под влиянием | |
C , [3] [5] C ++ , [6] Bourne shell , KornShell , Bash , Steelman , Ada , Python , [7] Seed7 , Mary , S3 |
Эта статья содержит символы Unicode 6.0 « Разные технические ». Без надлежащей поддержки рендеринга вы можете увидеть вопросительные знаки, квадраты или другие символы вместо чего-то вроде «₁₀» ( десятичный знак экспоненты U + 23E8 TTF ). |
АЛГОЛ 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:
Алгол 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.
Первая реализация стандарта, основанная на проекте отчета конца 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]
Год | Мероприятие | Автор |
---|---|---|
Март 1959 г. | Бюллетень ALGOL, выпуск 1 (первый) | Питер Наур / ACM |
Февраль 1968 г. | Опубликован проект отчета (DR) [34] | Рабочая группа 2.1 ИФИП |
Март 1968 г. | Заключительный отчет по Алгол 68 r0 представлен на встрече в Мюнхене | Рабочая группа 2.1 ИФИП |
Июнь 1968 г. | Встреча в Тиррении, Италия | Рабочая группа 2.1 ИФИП |
Август 1968 г. | Встреча в Норт-Бервике, Шотландия | Рабочая группа 2.1 ИФИП |
Декабрь 1968 г. | АЛГОЛ 68 Заключительный отчет r0 представлен на встрече в Мюнхене | Рабочая группа 2.1 ИФИП |
Апрель 1970 г. | Алгол 68-R (R) под GEORGE 3 на ICL 1907F | Royal Signals и Radar Est. |
Сентябрь 1973 г. | Пересмотренный отчет Algol 68 [35] r1 опубликован | Рабочая группа 2.1 ИФИП |
1975 г. | АЛГОЛ 68C (C) - переносимый компилятор (zcode VM ) | С. Борн , Эндрю Биррелл и Майкл Гай |
Июнь 1975 г. | Г. Е. Хедрик и Алан Робертсон. Компилятор подмножества Алгола 68 штата Оклахома. 1975 Международная конференция по АЛГОЛу 68. | |
Июнь 1977 г. | Конференция Strathclyde ALGOL 68, Шотландия | ACM |
Май 1978 г. | Предложения для АЛГОЛА H - Суперязыка Алгола 68 [36] | А. П. Блэк, В. Дж. Рэйвард-Смит |
1984 | Полный компилятор ALGOL 68S (S) для Sun, SPARC и ПК | CH Линдси и др., Манчестер |
Август 1988 г. | Бюллетень ALGOL, выпуск 52 (последний) | Эд. CH Линдси / ACM |
Май 1997 г. | Algol68 S (S) опубликован в Интернете [37] | Чарльз Х. Линдси |
Ноябрь 2001 г. | Algol 68 Genie (G) опубликован в Интернете [38] (лицензия с открытым исходным кодом GNU GPL) | Марсель ван дер Веер |
«Ван Вейнгаарден однажды охарактеризовал четырех авторов, несколько иронично, как: Костер: транспуттер , Пек: синтаксис, Майлу: исполнитель, Ван Вейнгаарден: партийный идеолог». - Костер.
1968: На 20 декабря 1968 года «Заключительный отчет» (MR 101) был принят Рабочей группа, то впоследствии утвержденной Генеральной Ассамблеей ЮНЕСКО «s МФОЙ для публикации. Перевод стандарта был сделан на русский , немецкий , французский и болгарский , а затем на японский и китайский языки . [44] Стандарт был также доступен на шрифте Брайля .
1984: TC97 рассматривал АЛГОЛ 68 для стандартизации как «новый рабочий элемент» TC97 / N1642 [2] [3] [ постоянная мертвая ссылка ] . Западная Германия, Бельгия, Нидерланды, СССР и Чехословакия были готовы участвовать в разработке стандарта, но СССР и Чехословакия «не были подходящими членами правильных комитетов ISO» [4], и стандартизация ISO в Алголе 68 застопорилась. [5]
1988: Впоследствии АЛГОЛ 68 стал одним из стандартов ГОСТ в России.
Эта статья содержит символы Unicode 6.0 « Разные технические ». Без надлежащей поддержки рендеринга вы можете увидеть вопросительные знаки, квадраты или другие символы вместо чего-то вроде «₁₀» ( десятичный знак экспоненты U + 23E8 TTF ). |
Стандартный язык содержит около шестидесяти зарезервированных слов, обычно выделенных жирным шрифтом, а некоторые из них имеют эквиваленты «кратких символов»:
режим , 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 , канал , сема
Сложные типы можно создавать из более простых с помощью различных конструкторов типов:
Для некоторых примеров см. Сравнение АЛГОЛА 68 и C ++ .
Другие символы объявления включают: flex , heap , loc , ref , long , short , event S
Имя для режима (типа) может быть объявлено с помощью объявления режима , которое похоже на 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 . Принуждение может быть каскадным.
Шесть возможных принуждения называются депроцедурацией , разыменованием , объединением , расширением , греблей и опорожнением . Каждое принуждение, кроме объединения , предписывает соответствующее динамическое воздействие на связанные значения. Следовательно, многие примитивные действия могут быть запрограммированы неявно с помощью принуждения.
Сила контекста - разрешенные принуждения:
АЛГОЛ 68 имеет иерархию контекстов, которые определяют виды принуждения, доступные в определенной точке программы. Эти контексты:
Расположение контекста | Доступны принуждения | Примеры принуждения в контексте | ||||
---|---|---|---|---|---|---|
Правая сторона:
Также:
| Расширение происходит, если нет потери точности. Например: INT будет преобразовано в REAL, а REAL будет преобразовано в LONG REAL. Но не наоборот. Примеры: INT в LONG INT INT в REAL REAL в COMPL BITS в [] BOOL BYTES в STRING Переменная также может быть преобразована в массив длиной 1. Например: INT до [1] INT От REAL до [1] REALи т.п. | |||||
| Пример:
| |||||
| Примеры:REF REF BOOL на BOOL REF REF REF INT в INT | |||||
| Примеры:REF BOOL в REF BOOL REF REF INT на REF INT REF REF REF REAL на REF REAL REF REF REF REF STRUCT на REF STRUCT | |||||
LHS назначений, как "~" в: ~ := ... | Пример:
|
Дополнительные сведения о первичных, вторичных, третичных и четвертичных компонентах см. В разделе «Приоритет операторов» .
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 od Минимальная форма «предложения цикла» такова: операторы do od
Это считается «универсальным» циклом, полный синтаксис:
для i от 1 до -22 до -333, а i × i ≠ 4444 do ~ od
У конструкции есть несколько необычных аспектов:
int сумма sq: = 0;для меня пока print (("Пока:", i, новая строка)); сумма sq ≠ 70 ↑ 2делать сумма sq +: = i ↑ 2od
Последующие «расширения» к стандартному Algol68 позволили к синтаксическому элементу должны быть заменены UPTO и Downto для достижения небольшой оптимизации. В те же компиляторы также включены:
Дополнительные примеры можно найти в примерах кода ниже.
Алгол 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);
Пример использования для накидной случае из узла :
Algol68 r0 как в Заключительном отчете 1968 г.узел n: = "1234"; реальный r; int i; компл c; строка s case r, i, c, s :: = n in print (("реальный:", r)), print (("int:", я)), print (("компл:", c)), print (("строка:", s)) out print (("?:", n)) esac | Algol68 r1, как в Пересмотренном отчете 1973 г.узел n: = "1234"; # или n: = ПУСТО; # case n in ( void ): print (("void:", "EMPTY")), ( реальный r): print (("real:", r)), ( int i): print (("int:", i)), ( компл. c): print (("компл .:", c)), ( строка s): print (("строка:", s)) out print (("?:", n)) esac |
Объявления процедур ( 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 .
Программист может определять новые операторы, и как те, так и предопределенные операторы могут быть перегружены, а их приоритеты могут быть изменены кодером. В следующем примере оператор определяется 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 ; из)
ПРИО rity | Операция r0 и r1 | + Алгол68 r0 | + Алгол68 G |
---|---|---|---|
Фактически 12 (Начальная школа) | разыменование, депроцедура (~, ~), индексирование [~], гребля [~,], нарезка [~: ~], обозначения размеров длинные и короткие | производство | каррирование (~ ,,,), diag , trnsp , row , col |
Фактически 11 (Среднее) | of (выбор), loc & heap (генераторы) | → (выбор) | новые (генераторы) |
Это технически не операторы, а скорее « единицы, связанные с именами ».
ПРИО rity (третичный) | Algol68 "Достойные персонажи [6] " r0 & r1 | + Алгол68 r0 и r1 | + Алгол68 C, G | + Алгол68 r0 |
---|---|---|---|---|
10 | не ~, вверх , вниз , lwb , upb , -, abs , arg , bin , entier , leng , level , odd , repr , round , short | ¬, ↑, ↓, ⌊, ⌈ | норма , след , t , det , inv | lws , ups , ⎩, ⎧, btb , ctb |
ПРИО rity (третичный) | Algol68 "Достойные персонажи" r0 & r1 | + Алгол68 r0 и r1 | + Алгол68 C, G | + Алгол68 r0 |
---|---|---|---|---|
9 | + *, я | + ×, ⊥ | ! | |
8 | shl , shr , **, вверх , вниз , lwb , upb | ↑, ↓, ⌊, ⌈ | × ··· × , ^, lws , ups , ⎩, ⎧ | |
7 | *, /,%, больше ,% *, mod , elem | ×, ÷, ÷ ×, ÷ *,% ×, □ | ÷: | |
6 | -, + | |||
5 | <, lt , <=, le ,> =, ge ,>, gt | ≤, ≥ | ||
4 | eq =, ne ~ = / = | ≠, ¬ = | ||
3 | &, и | ∧ | / \ | |
2 | или | ∨ | \ / | |
1 | минусаб , плюсаб , таймсаб , диваб , овераб , модаб , плюсто , -:=, +:=, *:=, /:=, %:=, %*:=, +=: | ×:=, ÷:=, ÷×:=, ÷*:=, %×:= | minus, plus, div, overb, modb, ÷::=, prus |
Specific details:
These are technically not operators, rather they are considered "units associated with names"
priority (Quaternaries) | Algol68 "Worthy characters"r0&r1 | +Algol68r0&r1 | +Algol68C,G,R | +Algol68r0 |
---|---|---|---|---|
Effectively 0 | :=, is :=:, isnt :/=: :~=:, at @, ":", ";" | :≠: :¬=: | :=:=C, =:=R | ..=, .=, ct, ::, ctab, ::=, .., is not, "..", ".," |
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)
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 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.
The transput is considered to be of books, channels and files:
match
.establish, create, open, associate, lock, close, scratch
.char number, line number, page number
.space
, backspace
, newline
, newpage
.get good line, get good page, get good book
, and proc set=(ref file f, int page,line,char)void:
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" 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))
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)
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
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]
Both ALGOL 68C and ALGOL 68-R are written in ALGOL 68, effectively making ALGOL 68 an application of itself. Other applications include:
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:
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."
Representation | Code |
---|---|
Algol68 "strict" as typically published | ¢ underline or bold typeface ¢ mode xint = int; xint sum sq:=0; for i while sum sq≠70×70 do sum sq+:=i↑2 od |
Quote stropping (like wikitext) | 'pr' quote 'pr'
'mode' 'xint' = 'int';
'xint' sum sq:=0;
'for' i 'while' sum sq≠70×70
'do' sum sq+:=i↑2
'od' |
For a 7-bit character code compiler | .PR UPPER .PR
MODE XINT = INT;
XINT sum sq:=0;
FOR i WHILE sum sq/=70*70
DO sum sq+:=i**2
OD |
For a 6-bit character code compiler | .PR POINT .PR
.MODE .XINT = .INT;
.XINT SUM SQ:=0;
.FOR I .WHILE SUM SQ .NE 70*70
.DO SUM SQ .PLUSAB I .UP 2
.OD |
Algol68 using res stropping (reserved word) | .PR RES .PR
mode .xint = int;
.xint sum sq:=0;
for i while sum sq≠70×70
do sum sq+:=i↑2
od |
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 выб ~ в ~ либо ~ быв.
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) mode ℵ simplout = union (≮ℒ int≯, ≮ℒ real≯, ≮ℒ compl≯, bool, ≮ℒ bits≯, char, [ ] char); b) mode ℵ outtype = ¢ 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) mode ℵ simplin = union (≮ref ℒ int≯, ≮ref ℒ real≯, ≮ref ℒ compl≯, ref bool, ≮ref ℒ bits≯, ref char, ref [ ] char, ref string); d) mode ℵ intype = ¢ ... ¢; §10.3.2.3. Straightening a) op ℵ straightout = (outtype x) [ ] simplout: ¢ the result of "straightening" 'x' ¢; b) op ℵ straightin = (intype x) [ ] simplin: ¢ the result of straightening 'x' ¢;
Except where noted (with a superscript), the language described above is that of the "Revised Report(r1)".
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.
After the revision of the report, some extensions to the language have been proposed to widen the applicability:
ENVIRON
and USING
clauses from ALGOL 68C[56]So far, only partial parametrisation has been implemented, in Algol 68 Genie.
Name | Year | Purpose | State | Description | Target CPU | Licensing | Implementation language |
---|---|---|---|---|---|---|---|
Generalized ALGOL | 1962 | Scientific | NL | ALGOL for generalised grammars | |||
ALGOL YY | 1966 | Draft proposal | Intl | First version of Algol 68 | Specification | ACM | |
ALGOL 68DR | 1968 | Draft proposal | Intl | IFIP WG 2.1 Draft Report | Specification – March | ACM | |
ALGOL 68r0 | 1968 | Standard | Intl | IFIP WG 2.1 Final Report | Specification – August | ACM | |
ALGOL 68-RR | 1970 | Military | UK | ICL 1900 | ALGOL 60 | ||
EPOS ALGOLE | 1971 | Scientific | |||||
ALGOL 68RSRS | 1972 | Military | UK | Portable compiler system | ICL 2900/Series 39, Multics, VMS & C generator (1993) | Crown Copyright | ALGOL 68RS |
Algol 68 with areas | 1972 | Experimental & other | UK | Addition of areas to Algol 68 | |||
Mini ALGOL 68 | 1973 | Research | NL | "An interpreter for simple Algol 68 Programs" | Portable interpreter | Mathematisch Centrum | ALGOL 60 |
OREGANO | 1973 | Research | US | "The importance of implementation models." | UCLA | ||
ALGOL 68CC | 1975 | Scientific | UK | Cambridge Algol 68 | ICL, IBM 360, PDP 10 & Unix, Telefunken, Tesla & Z80 (1980)[57] | Cambridge | ALGOL 68C |
ALGOL 68 Revised Reportr1 | 1975 | Standard | Intl | IFIP WG 2.1 Revised Report | Specification | ACM | |
Algol HH | 1975 | Experimental & other | UK | Proposed extensions to the mode system of Algol 68 | Specification | ALGOL W | |
Odra Algol 68 | 1976 | practical uses | USSR/Poland | Odra 1204/IL | Soviet | ALGOL 60 | |
Oklahoma ALGOL 68 | 1976 | programming instruction | USA | Oklahoma State University implementation[58] | IBM 1130 and System/370/158 | Unknown | ANSI Fortran 66. |
Berlin ALGOL 68 | 1977 | Research | DE | "The Berlin ALGOL 68 implementation" &[59] | An Abstract ALGOL 68 Machine – machine independent Compiler | Technical University of Berlin | CDL 2 |
FLACCF | 1977 | Multi-purpose | CA | Revised Report complete implementation with debug features | System/370 | lease, Chion Corporation | Assembler |
ALGOL 68-RTRT | 1979 | Scientific | UK | Parallel ALGOL 68-R | |||
RS Algolrs | 1979 | Scientific | UK | ||||
ALGOL 68+ | 1980 | Scientific | NL | Proposed superlanguage of ALGOL 68[60] | |||
M-220 ALGOL 68 | USSR | M-220 | Soviet | EPSILON | |||
Leningrad ALGOL 68L | 1980 | Telecommunications | USSR | Full language + modules | IBM, DEC, CAMCOH, PS 1001 & PC | Soviet | |
Interactive ALGOL 68I | 1983 | UK | Incremental compilation | PC | Noncommercial shareware | ||
ALGOL 68SS | 1985 | Scientific | Intl | Sun version of ALGOL 68 | Sun-3, Sun SPARC (under SunOS 4.1 & Solaris 2), Atari ST (under GEMDOS), Acorn Archimedes (under RISC OS), VAX-11 under Ultrix-32 | ||
Algol68toC[61] (ctrans) | 1985 | Electronics | UK | ctrans from ELLA ALGOL 68RS | Portable C generator | Open-source software 1995 | ALGOL 68RS |
MK2 Interactive ALGOL 68 | 1992 | UK | Incremental compilation | PC | Noncommercial shareware[62] | ||
Algol 68 GenieG | 2001 | Full language | NL | Includes standard collateral clause | Portable interpreter | GPL | C |
Algol 68 Genie version 2.0.0 | 2010 | Full language | NL | Portable interpreter; optional compilation of selected units | GPL | C |
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.
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]
|
|
|
|journal=
(help)