Lecture
Ada Augusta Byron |
Ada’s high-level programming language is named for Augusta Ada Byron, Countess of Lovelace and daughter of English poet Lord Byron. She was an assistant, colleague and supporter of Charles Babbage, a mathematician and inventor of a computer called the analytic machine. With the help of Charles Babbage in 1830, she wrote an almost complete program on an analytical machine for calculating Bernoulli numbers. Therefore, the Countess can be called the first programmer in the world on a computer.
Ada, the name of the Countess, was developed on the initiative and with the assistance of the US Department of Defense. Studies undertaken in the early and mid-1970s showed that huge savings in software costs (about $ 24 billion over the period 1983-1999) can be obtained if the defense ministry uses a single programming language to solve all its problems. tasks instead of about 450 programming languages and incompatible dialects used by programmers.
The result of this study is the requirements for a new programming language that can replace most of the programming languages used within the US Department of Defense. The demands, which received the playful name “straw man”, were gradually detailed through extensive discussion both in the United States and abroad. The process involved US forces, foreign military organizations, industry, and universities. The detailing requirements received as a result of the next step were gradually called “wooden”, “iron” and, finally, “steel”.
Although the motivations for creating a new programming language were initially purely economic, it was strongly influenced by the desire to have a programming language aimed at solving important software development problems. Requirements for the new language contained such technical features as simplicity and completeness of the language, reliability, correctness and portability of programs, ease of support, the possibility of developing large programs, real-time programming, and error detection and correction. In support of the trend of transferring to multicomputers and the rejection of large computers, the requirements also included parallel programming, i.e. the ability to write programs whose components could be run in parallel on different computers or on a single computer quasi-parallel. An international competition was organized to develop a language that meets the listed requirements. Seventeen firms submitted their proposals, four of them were selected as semi-finalists. Interestingly, all the semi-finalists took Pascal as the basis for their languages. The winner of the competition was a programming language developed by a group of scientists under the leadership of J. Ishbia of CII Honeywell Bull. Having undergone a number of changes, this language was called Ada. After some time, the modified Ada language becomes the ANSI standard; further changes in the language were aimed at simplifying it and eliminating inconsistencies. The language of Hell was adopted as the ANSI standard in February 1983.
Another area of work for the US Department of Defense in standardizing its software was the project for grading compilers from the Hell language. The goal of this project is to develop a set of standard tests that the compiler must perform before it is fixed as implementing the standard of the Ada language. In parallel, the process of developing requirements for the environment of Hell programs and the interface between programs and users was initiated.
The Hell language is a modern programming language containing such features of pascal-like languages as type definitions, general control structures and subroutines. Moreover, in the language of Ada, many achievements of the theory of programming languages obtained after 1970 are collected. The language supports logical modularity, for which data, types and subroutines can all be packages. Physical modularity is achieved by separate compilation. Ada language supports real-time programming through parallelization and exception handling. System programming is supported by accessing system-dependent parameters and precision control in data representation.
The language of Hell introduces a rigorous programming discipline aimed at making programs more readable, reliable, portable, modular, efficient, etc. - i.e. possessing all the qualities of a good program. For example, the programmer must declare all objects, use objects according to their types, and refer to objects only in accordance with the rules of visibility of the Ada language. Let the programmer previously used for these purposes a language that does not possess the rigor that the Hell language prescribes. However, having written several non-trivial programs in the Ada language, the programmer will evaluate its rules, understand that the purpose of the limitations of the Ada language is to find a greater number of errors compared to other programming languages, earlier and automatically, and also to help the programmer to write good programs without constraining his creativity and ingenuity.
Abstractions | Object variables Object methods Class variables Class methods |
Yes Yes Not Not |
---|---|---|
Access limitation | For variables For methods |
Public, separate Public, separate |
Modularity | Types of modularity | Package (Specification-body) |
Hierarchy | Inheritance Generalized blocks Metaclasses |
Not Yes Not |
Typing | Strong typing Polymorphism |
Yes Not |
Parallelism | Multitasking | Yes (defined in language) |
Resilience | Object stability | Not |
(Born December 10, 1815)
It is well-known that since 1901, on December 10, the annual Nobel Prizes are given in memory of their founder Alfred Nobel, who died on this day in 1896. But there is one more, less well-known definition for this date, which, however, is directly related to the occupation of many of our readers, December 10 is called the Programmer's Day in honor of the first representative of this not too ancient profession Ada Augusta born on this day. Lovelace, the only daughter of the famous English poet George Gordon Byron and his wife Annabella Milbank.
Ada Augusta Byron was born on December 10, 1815; her parents broke up when the girl was two months old and she did not see her father anymore. Byron devoted his daughter several touching lines in Childe Harold's Pilgrimage, but he worried in advance in a letter to his cousin: "I hope that God will reward her with anything, but not with a poetic gift ..." the daughter of literary inclinations, the mother, who, in light of her dedication to the exact sciences, was called the "princess of the parallelogram" Ada received an excellent education, including in the field of mathematics. By 1834, she had her first acquaintance with the outstanding mathematician and inventor Charles Babidge (1791-1871), the creator of the first digital computer with program control, which he called "analytical".
Babbage's machine was conceived as a purely mechanical device with a possible drive from the steam engine, but contained a number of fundamental ideas characteristic of modern computers. It provided for work with addresses and command codes, data was entered using punched cards. The basics of programming were also laid by Babbage. Despite the nearly forty years of work of its creator, the car was never completed, ahead of not only the needs, but also the technical capabilities of its time. Many of the ideas of Babbage simply could not be implemented on the basis of mechanical devices and were only claimed a century later, with the development of the first electronic computers. It is clear that contemporaries referred to the work of Babbage as, at least, extravagant eccentricity. The wife of the famous English mathematician of that time, de Morgan, under whose leadership Ada Augusta studied mathematics, described their first visit to Babbage as follows: "While some of the guests looked at this amazing device with amazement, the savages saw the mirror for the first time or they hear a shot from a gun, Miss Byron, still very young, was able to understand the operation of the car and appreciated the great merit of the invention. " Babbage found in Ada not only a grateful listener, but also a loyal assistant. He sincerely attached to the girl, who was almost the same age as his early deceased daughter.
In 1835, Ada Byron married William, the eighteenth Lord King, who later became the first Earl of Lovelace. (In some Russian publications, the word Lovelace is associated with the title of the Lovelace family; this is a mistake: Lovelace is the name of the hero of the popular at the beginning of the last century Richardson novel "Clarice Garlo," which has become a common noun for red tape, seducer) The husband had nothing against his wife’s scientific studies and even encouraged her in them. True, appreciating her mental abilities, he lamented: "What a great general you could be!" The appearance of children temporarily distracted Ada from studying mathematics, but at the beginning of 1841 she wrote Babbage: "I hope that my head can be useful to you in realizing your goals and plans in the next three or four, and maybe even more years old".
At Babid's request, Ada began translating an essay by Italian military engineer Louis Frederico Menabrea (later a professor of mechanics at the University of Turin, one of the leaders in the struggle to unify Italy, from 1867 her prime minister and minister of foreign affairs). Menabrea in 1840, while listening to Babbage’s lectures in Turin, wrote them down in detail, and in his essay for the first time gave a complete description of Babbage’s analytical machine and his ideas on computation programming. He wrote: “The calculation process itself is carried out using algebraic formulas written on perforated maps, similar to those used in Jacquard looms. All mental work is reduced to writing formulas suitable for calculations made by the machine and some simple instructions in which sequences these calculations must be made. "
Lady Lovelace did not just translate the essay by Menabrea, but also provided him with extensive commentaries, which in sum nearly tripled the size of the original text. All comments, their general structure and content were discussed in detail and agreed with Babbage. Known for his intolerance to the opinions of others, Babbage, however, was delighted with the original studies of his student:
- "The more I read your notes, the more amazed you are by your intuition ... I do not want to part with your excellent philosophical consideration of my analytical machine ..."
The Menabrea book, with commentaries signed by the initials AAL (Ada Augusta Lovelace), was published in August 1843. Paying tribute to both authors, Babbage wrote: "The combination of these works (Menabrea and Lovelace) is for those who are able to follow the course of their reasoning, a clear demonstration that virtually any mathematical analysis operations can be performed using a machine." At the same time, Babbage did not completely reconcile with the concept of Ada, which Turing later called the sixth postulate of the opponents of the thinking machine idea: "The analytic machine does not pretend to create something really new. The machine can perform only what we can prescribe. "
In the comments of Lovelace, the first three computational programs in the world compiled by her for the Babbage machine were given. The simplest and most described of them is the program for solving a system of two linear algebraic equations with two unknowns. When analyzing this program, the concept of work cells (work variables) was first introduced and the idea of a consistent change in their content was used. One step from this idea remains to the assignment operator - one of the fundamental operations of all programming languages, including machine. The second program was compiled to calculate the values of the trigonometric function with multiple repetitions of a given sequence of computational operations; for this procedure, Lovelace introduced the concept of a cycle - one of the fundamental structures of structured programming. In the third program, designed to calculate Bernoulli numbers, recurrent nested loops were already used. In her comments, Lovelace also expressed a great conjecture that computational operations can be performed not only with numbers, but also with other objects, without which computers would have remained just powerful high-speed calculators.
After completing the translation and commentary, Ada suggested Babbage that she would advise those interested in using computers so that Babbage would not be distracted from the main work of bringing her analytical machine. But the time for computers has not come yet, the crowds of users were in no hurry to get advice from Lady Lovelace, moreover - in 1842, the British government refused Beidzhu in financial support for its development. Babbage was ready to do anything to get the necessary money. In particular, together with the Lovelace spouses, he was fascinated by the idea of creating a "truly scientific, mathematical" system of betting on the run, which would give a sure win. As one would expect, the “system” did not work and brought not only disappointment, but also great financial losses. Countess Lovelace turned out to be her strongest supporter - she continued to play hard, often even secretly from her husband and Babige, trying to improve the system. At this point, she lost almost all of her personal funds. In addition, in the early 50s, her health suddenly and sharply deteriorated, and in 1852 Ada Lovelace died at the age of 37, like her father, and was buried next to him in the family crypt Byron.
Ada Lovelace's name resurrected from non-existence in the mid-1930s in connection with the work of the English mathematician Alan Turing, who introduced the concept of a logical algorithmic structure, called the Turing machine, and the subsequent creation of the first electronic computers.
By the end of the 1970s, research conducted by the US Department of Defense revealed the absence of a high-level programming language that would support all the main stages of software development. The use of different programming languages in different applications led to the incompatibility of the developed programs, duplication of developments and other undesirable phenomena, including rising software costs, many times exceeding the cost of the computer itself. The way out of the crisis was seen in the development of a unified programming language, its support environment and application methodology. All three components of this project were developed very carefully with the involvement of the most qualified specialists from different countries. In May 1979, the language of Hell, named after Ada Augusta Lovelace, and proposed by a group led by Frenchman Jean Ishbia, was declared the winner in the language development contest. The prototype of this language was a programming language, named after Blaise Pascal, who at the age of nineteen, in 1624, developed the project "Pascalines" or, in a different way, "Paskalev wheels" - the first mechanical computer. With the advent and widespread use of personal computers, the language of Ada has largely lost its significance, but is still used as a high-level language for developing real-time programs.
It is curious that in honor of Ada Lovelace two small cities are also named in America - in the states of Alabama and Oklahoma. Oklahoma also has a college named after her. It seems to be a little, but at the same time, there are people who sincerely believe that today Ada Lovelace’s fame (or at least popularity) has eclipsed her famous father’s fame, and that her contribution to world civilization, at least , commensurate with the contribution of the great poet.
Ada is a universal programming language that includes tools for creating parallel programs. The official programming language of the US Department of Defense. There are many compilers for a variety of platforms. Current official version: Ada-95 (latest - Ada-2003)
В деле разработки новых языков программирования много спорных моментов, примером которых может служить ADA - новейшее средство программирования, разработанное Министерством обороны США и отличающееся черезвычайно большими возможностями. Язык программирования ADA, как известно, был разработан с целью замены устаревших и все менее используемых языков, таких как COBOL и FORTRAN. Трудности заключаются в том, что цикл замены одного языка программирования другим охватывает период времени от 20 до 30 лет и не начинается до тех пор, пока мы не убедимся на деле, что ныне существующие языки больше не отвечают нашим требованиям. Мы можем ускорить этот процесс, начав немедленную замену устаревших языков языком ADA. При этом, когда мы придем к выводу, что ADA уже устарел, замена на него только только успеет завершиться. У нового поколения разработчиков языков программирования появилась тенденция называть разработанные ими языки именами реальных людей, а не прибегать к обычным акронимам. Так язык PASCAL получил наименование в честь первого создателя счетных машин, а язык ADA назван в честь первого программиста. ADA
The ADA language is named after Augusta Ada Byron (Augusta Ada Byron), used almost exclusively by the Department of Defense and other US government agencies. Experts attributed ADA to mediocre languages, since it is difficult to learn (the government was not always guided by logic). This language was adopted by the standard in US government and was approved by the Department of Defense in 1979.
Species: Atree ADA, Janus ADA, Meridian ADA .
All modern industrial languages provide essentially the same basic set of possibilities, differing not in what they allow you to do, but how exactly they allow it to be done. However, Ada, at least in two aspects, extends the standard set of possibilities for modern languages. First, Ada provides high-level asynchronous programming tools. Secondly, it is the only language that can be called modular without reservation.
Пример такой просто необходим для того, чтобы опровергнуть достаточно распространенный миф о том, что Ада - большой, сложный и "тяжелый" язык, пригодный лишь для написания сверхбольших и сверхсложных систем. На самом же деле, Ада может применяться для разработки небольших и средних программ с тем же успехом, как и современные клоны Си, Паскаля, Бейсика и Java. Так, классический пример программы "Hello, World!" выглядит на Аде следующим образом:
Легко видеть, что код на Аде похож на код на Паскале, который был выбран в качестве его прототипа. Первая строка описывает связь данного компилируемого модуля с другими модулями - указывается, что подпрограмма Hello_World должна компилироваться совместно с модулем Ada.Text_IO, который является компонентом предопределенной библиотеки.
The following program defines two asynchronous processes [1]
В разделе локальных объявлений процедуры Tasking_Example описывается задача Outputter (строка 6, строки с 8 по 17 содержат тело этой задачи). Когда управление в процессе, соответствующем процедуре Tasking_Example, доходит до строки 20, перед тем, как выполнить этот первый оператор, запускается процесс, соответствующий задаче Outputter, после чего два этих процесса живут и асинхронно выполняются независимо друг от друга. Выполнение оператора задержки (строки 14 и 20) состоит в приостановке соответствующего процесса на указанное количество секунд. Таким образом, процесс Tasking_Example приостанавливается на 20 секунд, а в это время процесс Outputter начинает печатать значения увеличивающегося на единицу счетчика, приостанавливаясь на одну секунду после вывода каждого значения. По истечении 20 секунд процесс Tasking_Example устанавливает флаг Finished в положение "истина", в результате завершается цикл в процессе Outputter. Спецификация переменной Finished как атомарного объекта данных (строка 4) делает невозможным одновременное чтение и изменение значения этой переменной.
Далее представлен шаблон функции, позволяющей покомпонентно складывать два одномерных массива. Этот шаблон может быть настроен на произвольный тип, являющийся одномерным массивом, для компонентов которого определены операции присваивания и сложения ("сложение" не обязано быть арифметическим сложением).
Строки 1-6 содержат объявление настраиваемой функции, а строки 8-20 - ее тело. Содержательно, параметром настройки является произвольный одномерный регулярный тип с неуточненным индексным диапазоном (строка 4), про которого известно только, что тип компонента у него произвольный, однако для компонентов определена операция присваивания (строка 2), тип индекса - произвольный дискретный (строка 4). Поскольку нам предстоит покомпонентно складывать два массива, надо знать, что такое операция сложения для типа компонентов. Так как это произвольный тип, мы вынуждены передавать сложение для типа компонента как формальный параметр настройки (строка 5).
В теле функции мы первым делом проверяем, совпадают ли длины операндов (строка 12), иначе покомпонентное сложение не имеет смысла. Совпадение длин операндов не гарантирует совпадение индексных диапазонов, поэтому в цикле по индексному диапазону первого аргумента (строка 15) нам необходимо каждый раз вычислять индекс соответствующего компонента второго аргумента. Мы лишены возможности сделать это для типа Index, так как знаем про него только, что он дискретен, поэтому переходим от значения дискретного типа к его порядковому номеру (атрибут 'Pos), вычисляем необходимый сдвиг для порядкового номера и возвращаемся к соответствующему значению типа Index (атрибут 'Val).
Заметим, что параметры (настраиваемой) функции "+" Left и Right объявлены как имеющие тип Arr, индексный диапазон которого не уточнен. Однако Left и Right - это формальные параметры, на место которых при вызове (результата конкретизации) функции "+" будут подставлены конкретные массивы с известными индексными диапазонами. Мы же в теле функции "+" пользуемся атрибутами массивов ('Range, 'First, 'Length), чтобы из объекта получить информацию о его индексном диапазоне.
Язык BABBAGE основан на элементах языков, которые были открыты после того, как было завершено создание языка ADA. К. А. Р. Хоор в своей лекции, за которую Ассоциация по вычислительной технике в 1980 году присудила ему премию Тьюринга, говорил о двух путях разработки программного обеспечения. Один путь заключается в том, чтобы сделать программу настолько простой, что становится полностью очевидно отсутствие каких-либо недостатков. А другой путь состоит в том, чтобы сделать программу настолько сложной, что это исключало бы всякую возможность каких-либо погрешностей. Разработчики языка BABBAGE выбрали третий путь, т.е. создать язык, который содержит только явные недостатки. Программы на BABBAGE отличаются такой низкой надежностью, что процедуры профилактического контроля можно начинать до того, как интеграция всей системы будет завершена.
Это служит гарантией постоянного роста спроса на продукцию разработчиков на рынке сбыта в области обработки данных.
Как и в языке PASCAL в языке ADA используется принцип "строгой печати" с целью избежать появления ошибок, которые могут быть результатом смешения различных типов данных.
Разработчики языка BABBAGE выступили в защиту принципа "надежной печати" с тем, чтобы избежать ошибок, появляющихся в результате неправильного написания слов в программе пользователя. В последующих версиях языка BABBAGE станет возможным применение "печати по слепому методу", что позволит удовлетворить давно назревшие требования пользователей.
It is a controversial issue that has been discussed for subfunctions. Some developers advocate "call by name", others prefer "call by value". The BABBAGE language uses a new method - "call by phone". This method has been especially useful when it comes to data processing.
The ADA language is based on the idea of portability. In the process of developing the BABBAGE language, developers primarily take into account the portability of the equipment. In the end, what is the use of a computer if the customer cannot always have the machine at hand or the software is unbearable.
It is known that the development of a programming language is successful if it finds financial support from the government. The development of the COBOL language, for example, was funded by the government, and the ADA language by the Ministry of Defense. After long negotiations, the Ministry of Health agreed to provide financial support to the developers of the BABBAGE language.
In the ADA language, sublanguage was not allowed for a long time. The basis of the BABBAGE language, to increase its flexibility, is the possibility of expanding the language. Each user can and must determine the size of his version of the program language.
The controversial question about the size of BABBAGE disappears, since each user himself determines the size of the language in accordance with its requirements. BABBAGE is thus an ideal language for generating a compiler version in each case.
Below are examples that can give some insight into the BABBAGE language.
In structural programming languages, the replacement of GOTO control transfer operators and multi-path conditional jumps with a simpler IF-THEN-ELSE structure was prohibited. In the BABBAGE language, there are several new conditional statements that serve as final terms in the structure of the user program:
WHAT IF (what if)
used in programming languages; the transition is performed before checking the controlled condition;
OR ELSE (otherwise)
the presence of a variant, as, for example, in the phrase "Add these two numbers, OR ELSE (or otherwise)";
WHY NOT? (why not?)
executes the code that follows in no matter what order;
WHO ELSE? (who else?)
used for polling during I / O operations;
ELSEWHERE (somewhere else)
is used to indicate that the user program is somewhere else, while
he believes she is here;
GOING GOING GONE (I'm going gone)
used to write non-structured programs; performs an arbitrary transition to another part of the user program; performs the work of 10 GOTO operators. For many years, FOR has been used in languages.
(in progress), DO UNTIL (perform until), DO WHILE
(execute while) and others to designate a loop (LOOP).
Exploring this direction, the developers of the BABBAGE language suggest
The following statements designate the program cycle:
DON'N DO WHILE NOT (do not run despite)
this cycle is not executed if the condition being monitored is not false (or if it is midday on Friday);
DIDN'T DO (not performed)
the loop is executed once and stops the further execution of any cycles;
CAN'T DO (impossible to do)
looping cannot continue;
WON'T DO (failure to perform)
the CPU pauses the execution of the program, since it detects errors in the code of the program cycle being executed; program execution can be resumed if "May I?"
("May I?");
WIGHT DO (you can not perform)
depends on what decision will be made by the central processor; execution if the CPU is in working condition; stopping execution if the CPU is in the stop state, or if the CPU is in the stop state by mistake;
DO ONTO OTHERS (in everything you want to do with you, do so with others)
it is used when recording the main cycle of systems operating in the time-sharing mode, in order to use in these systems a single way to implement relationships between individual users;
DO BACH (to portray Bach)
used to record time cycles for computer generated music (determining the desired rhythm).
Each structured language that meets the latest requirements has a CASE operator for implementing multi-branch branching. So in the ALGOL language there is a CASE with indexing, and in the PASCAL language there is an operator with identification. Those. in these languages the choice is not very large. In the BABBAGE language, on the contrary, there are a number of operators of this class:
JUST IN CASE (just in case)
intended for processing of spare explanations and last-minute information; allows the user to perform a multiplication by zero for the purpose of correction if a division by zero is accidentally performed; the execution of the inverse (restorative) action is also allowed, and after an accidental multiplication;
BRIFF CASE (short record case)
designed to ensure the brevity of the program;
OPEN AND SHUT CASE (case of "open and close")
using this operator, no proof of correctness is required;
IN ANY CASE (in any case)
this operator always means working condition;
HOPELESS CASE (hopeless case)
this operator always means inoperative;
BASKET CASE (desperate)
the operator really means a hopeless state.
The staff members of the BABBAGE language development team are constantly working on new features of the language, which will contribute to the continuous growth of the level of effectiveness of this language when it is used by customers. For example, the developers of the BABBAGE language are currently busy working on the ALMOST EQUAL SIGN ("almost the same sign") operator used to compare two floating point numbers. The work on this new nuance has already overcome significant difficulties.
No language, no matter what it is, can be used on its own. And for the BABBAGE language, a thoroughly developed operating system is absolutely necessary. After several attempts to use the existing systems, the group decided to write their own "virtual" operating system. Anyone knows the virtual memory operating system. But the staff of the group for the development of language BABBAGE made an attempt to find a slightly different solution, going far away.
The new operating system is called the virtual time operating system (VTOS). While virtual memory systems provide virtual memory properties of a computer, VTOS performs the same function with respect to processor time. As a result, the computer can simultaneously work with an unlimited number of tasks. Like the virtual memory system, which physically stores some of the data in the memory on disk, VTOS must also apply some tricks to achieve its goal. Although the user is confident that all his tasks are being performed at the current time, some of these tasks will actually be carried out next week.
As you can see, the BABBAGE language is still under development. The BABBAGE development team needs suggestions from specialists on new tools for this powerful new programming language. The author of the article, being one of the employees of the development team, appeals to all those working in the field of computer-aided data processing with a request to support the group in developing a new programming language (all offers from all those who wish to participate in the group will be accepted) .
Most likely you think that a compiler for such a powerful language as Ada is very, very expensive, but you are mistaken, you might be surprised, but one of the most powerful and popular compilers with Ady95, GNAT (Gnu / New york University Ada Translator) will not cost you a penny (with the exception of technical support, but only if you want to have it).
GNAT can be downloaded from the ftp://cs.nyu.edu FTP server in the / pub / gnat directory. It contains various versions of GNAT for various operating systems such as Unix, including SunOS / Solaris, Linux, NetBSD, SGI IRIX, IBM's AIX, DEC's Digital Unix.
There are also versions of GNAT for WinNT, Win95, MacOS, and even a version for DOS called "EZ2Load".
The Hell language provides developers with the perfect combination of integrity, consistency, reliability and efficiency. The language supports creative creativity and innovation, while at the same time ensuring the discipline and industrial level of software development required for the implementation of software systems of great importance.
Ada-2012
Ada Resource
Download the free version of the Ada compiler for WindowsGCC-Ada
Download the free version of the AdaCore compiler public GNAT
Download Atego Visual-Ada Trial Version: Object-Ada for Windows
Virtually all information on the Ada language and Ada technologies available on the Web can be found if one of the three sites is used as the starting point of the search: www.adahome.com, www.adaic.org, www.acm.org/sigada . Recently, the Russian-language website www.ada-ru.org was created by the enthusiasts of the Ada language. An annotated bibliography of books on the language of Hell, published in Russian, can be found at faqs.org.ru/progr/other_l/adafaq2.htm.
So, I think it's time to start this training. Of course, this is not a complete tutorial, this is just a brief introduction that will show you the basic structure of the program in the language of Hell and give you some ready-to-compile examples.
First I want the reader to find out what Ada is. Like her predecessor, Pascal, and her cousin C, Ada is a structured language. In other words, the program in Ada is an organized sequence of different sections, while in non-structural languages such as Basic, you can write anything and anywhere.
Also, Ade has his own terminology, and I will continue to use several such words, the meaning of which you may not be familiar with:
All programs in Ada have the following basic structure:
with PacketName; use Pack_Name; procedure Procedure_name Variable: Some_Type_type; begin Offer_1; Offer_2; end ProcessName;
ProcedureName is often the name of the program.
(Note: Unlike Pascal, there is no dedicated begin - end block, any program at the library level (that is, not embedded in another procedure / function) without parameters can be considered a program).
Place where it is written Variable: Some_Type of Value is a variable declaration. Perhaps you ask, what does "Some_Type_Signation" mean? This means what type of values can be stored in a variable. In other words, if you want to have a variable for integers, you need to write Variable: Integer; . If you need numbers with a comma, then Variable: Float; etc.
Semicolons are used to complete a variable declaration or more generally any program clause, allowing you to place more than one variable or clause on a line.
(note: in Pascal they share sentences, as a result there are several exceptions to the rules! And as a result of the chosen approach in Ada, their placement is made at a more intuitive level).
The begin instruction begins a sequence of real program commands.
Offer_1; and Offer_1; they really don't mean anything in Hell; in the real program in their place will be real commands, which will perform the actions we need.
Offer end Name_Procedure; completes the program command sequence. Now I can tell you that this little "demo" program was needed just to show you the structure of the program, but now we can look at the real work program. By tradition, it will be, we can say, a classic ;-) program that displays "Hello World", which is usually used when you first meet a new language.
with Ada.Text_IO; use Ada.Text_IO; procedure Hello_World is - And we don’t need variables here :) begin Put ("Hello world!"); end Hello_World;
The "Text_IO" package contains many functions for input / output operations;
It is used by programs that need to output and receive text.
(note: as in C for many reasons, there are no "built-in" operations for I / O, but there is a standard package of such operations).
I also have to say behind what to write "Ada." before "Text_IO". Since Ada can interact with many languages - for example, you can associate procedures in C or Cobol with your program - and it may happen that you have many libraries with hundreds of packages, so you need to specify where to get them.
(note translation: in Ada, you can organize a set of packages in a certain hierarchical structure with mutual relationships between the code in them. In this case, Text_IO is a child package from the Ada package).
The procedure (and the program in this case) is called "Hello_World." The sentences "with" and "use" allow you to use commands from them in our program. If you want to run this program, you can save it as hello_world.ada . Note: if you use GNAT you must save it as hello_world. adb .
Since this program does nothing other than printing a few words on the screen, we did not need to declare any variables, so the place in which it is usually done remains empty. Pay also attention to the double dash (-) before "And we do not need variables here :)". These dashes tell the compiler that this line is a comment . A comment is a line of text that the compiler ignores. Therefore, if you want to add the line “We don’t need variables here :)” in the program and then run it, you must add a double dash before it, otherwise the compiler will think that you wanted to use “And we don’t need variables here :)” as the description of the variable, naturally, does not understand anything and will give you an error message. Put clause ("Hello world!"); serves to print the text on the screen.
Even if it seems to you that using brackets complicates things, they are still needed. You can’t just take and write "Put" Hello world! ";"!
Also note that many names begin with capital letters. Notice also for many capital letters ("Text_IO" for example). It is not necessary to do this on a mandatory basis, but it is still advisable to do so for the convenience of reading your source code.
The next program is somewhat more complicated than the previous one. She asks the user for his / her name and then prints it on the screen along with other text:
with Ada.Text_IO; use Ada.Text_IO; procedure Get_Name is Name: String (1..80); Length: Integer; begin Put ("Enter your name>"); Get_Line (Name, Length); New_Line; Put ("Hello"); Put (Name (1..Length)); Put ("I think you will like to study Hell!"); end Get_Name;
How does all this work? We already know what Text_IO is and the Get_Name is clause speaks for itself
The variable Name contains the name entered by the user, and the type String (1..80) tells the compiler that Name is a string variable with a length of up to 80 characters. The second variable, Length , is an integer used to store the actual length of the string entered by the user.
And now about the rest: when the program is running, it prints "Enter your name>" and then waits for its input from the user. after he enters the name and presses Enter, the program skips the line ( New_Line; ) and prints "Hello [username], I think you will like to learn Hell!".
Perhaps you have a question "Is there a graphical programming environment (IDE) for Ada?". Yes, there are such, one of them, called ObjectAda, is supplied by Aonix, www.aonix.com (Note: This product is built in the spirit of Microsoft's IDE for Visual C ++)
ObjectAda exists in two versions for both MS Windows and X-Windows (X-Windows is the standard Unix window graphics system.)
However, note that this is a commercial product, though it is available for free download in a lightweight version and weighs about 60 ~ 70Mb.
Ada is Pascal that has been brought to its logical conclusion (at this stage in the development of __ programming). Ada is a universal programming language and the most powerful tool for software engineering. Equally suitable for writing "toothpicks" of 50 lines for one or two runs and for huge, particularly reliable real-time systems. It is strictly defined by the language standard. The language has built-in parallel programming tools, support for multilingual modules, handling exceptional situations. Talk about her excessive complexity is nonsense, caused by the fact that she was ahead of her time for 6.10. A powerful tool cannot be simple - “We have duplicates simple” ((c) “Monday ...”, Strugatsky), but I can’t call it too complicated either. Ada'e inherent severity, consistency, orthogonality, symmetry. It is conservative in a good way, despite the fact that revolutionary concepts were introduced into it, which were not understood and not accepted by gray fortran-coders of the early 1980s, which explains its relatively small distribution. The first standard came out in '83, the second standard came out in '95, which expanded and symmetrized the language. Ada's is characterized by very strict adherence to the standard, which makes programs on it relatively easy to transfer from platform to platform. !) Аналогии: Ada -- это Парфенон среди языков программирования, она величественна, изящна, строга и прекрасна. Если считать, что Pascal это МиГ-21, то Modula-2 это ( ранние версии ) МиГ-29 и ( нынешнее состояние ) МиГ-33, а Ada'83 -- Су-27, и Ada'95 -- Су-37, и, продолжая аналогию, C -- F-104, C++ -- F-117 ( much noise about nothing |) ). > Q 2: А чем Ada95 отличается от Ada83? Насколько я понял, > Q 2: в Ada95 есть ООП? Вот еще отличия: - иерархические библиотеки (child units); - пассивные мониторы наряду (protected records) с активными (tasks); - дополнительные средства управления паралеллизмом (асинхронная передача управления); - стандартные библиотеки для важнейших областей (системное программирование, системы реального времени, распределенные системы, информационные системы, численные рассчеты); - "мелочевка" типа ссылок на подпрограммы и возможность связывать сообщение с возбуждаемым исключением; > Q 3: Насколько я понял, в Ada95 есть ООП? А как оно > Q 3: реализуется? Подлинное там ООП (как на функциональных > Q 3: языках) или паскале-си подобное? "Паскале-си-подобное", хотя по форме на первый взгляд сильно отличается.
Основной документ по Ada'е -- "Language Reference Manual", обычно называемый просто "Стандарт" или "RM95" ( "RM 95", а то и просто "RM" ), некоторые по старинке говорят "LRM", но это -- общепринятое сокращение для стандарта Ады-83. Изложено, как и положено стандарту, суховато, но строго, с примерами и ссылками на смежные вопросы. В отличие от пары-тройки других "стандартов", которые мне привелось посмотреть, это, действительно, Стандарт, а не рассуждения на тему об очередной версии компилятора и не учебник программирования на базе данного языка, но, между тем, он вполне пригоден для чтения. Второй документ -- "Ada 95 Rationale" ( обычно -- "Rationale" ). Это изложение и _обоснование_ базовых _проектных__решений_ языка (ответы на вопросы "а почему сделано именно так?") и демонстрация этих решений в деле. Соответственно, более вольное, чем Стандарт, кое в чем менее полное, а кое в чем более ппространное. С развернутыми примерами, пояснениями, аналогиями и прочей весьма полезной "белетристикой". Читается как хороший детектив. Литературные достоинства ( без тени иронии ) этого документа отмечены не только мной. Я бы настоятельно рекомедовал эту книгу в качестве именно _учебника_ для подготовленного и _мотивированного_ читателя ( такому читателю нет резона тратить время на традиционные университетские учебники ), а RM использовать как справочник.
Сергей Рыбин, Василий Фофанов
Если спросить отечественного ИТ-специалиста: "Что такое Ада?", большинство лишь удивленно пожмет плечами, а кто-то даже скажет, что это мертвый язык, когда-то придуманный Пентагоном, а ныне практически не используемый. На самом же деле Ада и сегодня – вполне благополучный и активно применяемый в различных областях язык программирования. Правда, большинство российских программистов знают о нем мало.
Наверное, каждый, кому приходилось пользоваться четырнадцатой линией парижского метрополитена, удивлялся, впервые увидев поезд, в котором нет кабины машиниста. Движение поездов на этой линии полностью управляется Ада-программой.
Несмотря ни на что, в
продолжение следует...
Часть 1 ADA programming language
Часть 2 Почему язык Ада? - ADA programming language
Comments
To leave a comment
Programming Languages and Methods / Translation Theory
Terms: Programming Languages and Methods / Translation Theory