لغات البرمجة Programming Languages إعــــــــــداد Dr. Eng. Salah Abd-Elazim Mohammed دكتور مهندس/ صلاح عبد العظيم محمد



Download 140.47 Kb.
Date28.01.2017
Size140.47 Kb.
#9434
جامعة أم القرى

الكلية الجامعية بالجموم


لغات البرمجة

Programming Languages

إعــــــــــداد

Dr. Eng.

Salah Abd-Elazim Mohammed

دكتور مهندس/ صلاح عبد العظيم محمد

1434- 1435

Chapter (1)

مدخل إلى لغات البرمجة

Programming Languages Approach

1 Introduction


A program is a set of instructions that tell the computer to do various things; commands are usually written in one or other languages specially designed for the purpose. A programming language is a notation for writing programs, which are specifications of a computation or algorithm. A computer programming language is a language used to write computer programs, which involve a computer performing some kind of computation or algorithm and possibly control external devices such as printers, disk drives, robots, and so on.

2 Programming language generations

So far there are five generations of programming languages have been defined. These ranges from machine level languages (1GL) to languages necessary for AI & Neural Networks (5GL). There are strong relation or parallel relation between the development of both computer and programming language. A brief introduction of each of the five generations is given below:




2.1 First Generation Programming Language (Machine Code)

First generation computers used vacuum tubes for circuitry and magnetic drums for memory and they relied on machine language, the lowest-level programming language understood by computers, which are string of 0's and 1's.

First generation of programming language refers to machine language. Machine language is lower level language which uses object code (sometimes also known as machine code). Object code is the combination of binary digits. These languages directly talk to hardware.

While the programs were small, all operations, data and memory had to be managed by hand in binary.



  • Introduced in the 1940s

  • Instructions/Data entered directly in binary

  • Memory must be managed by hand in binary

  • Very difficult to edit/debug

  • Simple programs only

Example:


0010001000000100

0010010000000101

0001011001000010

0011011000000011

1111000000100101

0000000000000101

0000000000000110

0000000000000000






Figure1: A machine language program

In this program, each line of code contains 16 bits or binary digits. A line of 16 bits represents either a single machine language instruction or a single data value. The last three lines of code happen to represent data values—the integers 5, 6, and 0—using 16-bit twos complement notation. The first five lines

of code represent program instructions. Program execution begins with the first line of code, which is fetched from memory, decoded (interpreted), and executed.

To decode or interpret an instruction, the programmer (and the hardware) must recognize the first 4 bits of the line of code as an opcode, which indicates the type of operation to be performed. The remaining 12 bits contain codes for the instruction’s operands. The operand codes are either the numbers of machine registers or relate to the addresses of other data or instructions stored in memory. For example, the first instruction, 0010001000000100, contains an opcode and codes for two operands.

The opcode 0010 says, “copy a number from a memory location to a machine register” (machine registers are high-speed memory cells that hold data for arithmetic and logic computations). The number of the register, 001, is found in the next 3 bits. The remaining 9 bits represent an integer offset from the address of the next instruction.

2.2 Second Generation Programming Language (Assembly)
In second generation of computers the Transistors replaced vacuum tubes. The transistor allowing computers to become smaller, faster, cheaper, more energy-efficient and more reliable. Second generation of languages is near to low level language which is known as assembly language. Assembly languages are the interface between Machine level languages and High level languages.

Second-generation computers moved from binary machine language to symbolic, or assembly, languages, which allowed programmers to specify instructions in words, using symbols looks like this:

ADD 12,8


An assembler converts the assembly language statements into machine language.

Just like with machine code these instructions are specific to a particular family of processor. Assembly language is supported by computer architecture.



Assembly languages has the following data:

  • Introduced in the 1950s

  • Written by a programmer in an intermediate instruction language which is later compiled into binary instructions

  • Specific to platform architecture

  • Designed to support logical structure.


.ORIG x3000 ; Address (in hexadecimal) of the first instruction

LD R1, FIRST ; Copy the number in memory location FIRST to register R1

LD R2, SECOND ; Copy the number in memory location SECOND to register R2

ADD R3, R2, R1 ; Add the numbers in R1 and R2 and ; ; place the sum in register R3

ST R3, SUM ; Copy the number in R3 to memory ; ; location SUM

HALT ; Halt the program

FIRST .FILL #5 ; Location FIRST contains decimal 5

SECOND .FILL #6 ; Location SECOND contains ; decimal 6

SUM .BLKW #1 ; Location SUM (contains 0 by default)

.END ; End of program


Example:


Figure 2 An assembly language program that adds two numbers

Figure 2 shows the machine language program of Figure 1 after it has been “disassembled” into the LC-3 assembly language. It is now possible for a human being to read what the program does. The program adds the numbers in the variables FIRST and SECOND and stores the result in the variable SUM. In this code, the symbolic labels FIRST, SECOND, and SUM name memory locations containing data, the labels R1, R2, and R3 name machine registers, and the labels LD, ADD, ST, and HALT name opcodes. The program is also commented (the text following each semicolon) to clarify what it does for the human reader.


2.3 - Third Generation Programming Language (H.L.L)

In Third Generation computers integrated circuits replaced transistors, so the language in this period is completely moved from symbolic language to high level language. The compilers are designed for each language. A compiler converts the statements of a specific high-level programming language into machine language.



Third Generation programming languages are High level Programming languages like JAVA, Fortran, Cobol, Basic & C which can be classified as general purpose programming.  However, they all share great enhancements in logical structure over assembly language.

The Language in this period has the following characteristics:

  • Introduced in the 1950s

  • Driven by desire for reduction in bugs, increases in code reuse

  • Based on natural language

  • Often designed with structured programming in mind

Example:

int first = 5;

int second = 6;

int sum = first + second;



2.4- Fourth Generation Programming Language

In this period the technology is developed, the microprocessor / VLSI (Very Large Scale Integrated) brought the fourth generation of computers, as thousands of integrated circuits were built onto a single silicon chip. The computers became more powerful, they could be linked together to form networks, which eventually led to the development of the Internet. Also, this generation saw the development of GUIs.



Fourth-generation language is designed to be closer to human language than a 3GL language. Fourth generation programming languages are more aimed at problem solving. These languages are willing to run on many different families of processor (platform independent ).These are generally either databases languages or internet languages. Languages for accessing databases are often described as 4GLs like SQL (Structured Query Language. Also internet languages such as Java and HTML are considered as 4GL language.

General characteristics of 4GL are:



  • Closer to human languages

  • Portable

  • Database supportive

  • Simple and requires less effort than 3GL


Define a class

Public Class Class1

Public Function sum(ByRef x As Integer, ByRef y As Integer) As Integer

Return x + y

End Function

Public Function de(ByRef x As Integer, ByRef y As Integer) As Integer

Return x - y

End Function

Public Function mul(ByRef x As Integer, ByRef y As Integer) As Integer

Return x * y

End Function

Public Function divi(ByRef x As Integer, ByRef y As Integer) As Single

Return x / y

End Function

End Class

Calling the class

Dim aaa As New Class1

MsgBox(aaa.sum(2, 2))

Figure 3


2.5. Fifth Generation Programming Language

Fifth generation computing devices, based on (AI) artificial intelligence, are still in development. The goal of fifth-generation computing is to develop devices that respond to natural language input and are capable of learning. Prolog is the famous language in this generation. It depends on the facts, rules, then construct logical statement, then queries to deduce the solution. Languages used for writing programs for Artificial Intelligence, come under 5GL.



General characteristics of 5GL are:

  • Introduced in the 1990s

  • Used for AI Research

3. Abstractions in Programming Languages

We have noted the essential role that abstraction plays in making programs easier for people to read. In this section, we briefly describe common abstractions that programming lauages provide to express computation and give an indication of where they are studied in more detail in subsequent chapters. Programming language abstractions fall into two general categories: data abstraction and control abstraction. Data abstractions simplify for human users the behavior and attributes of data, such as numbers, character strings, and search trees. Control abstractions simplify properties of the transfer of control, that is, the modification of the execution path of a program based on the situation at hand. Examples of control abstractions are loops, conditional statements, and procedure calls.



3.1 Data: Basic Abstractions

Basic data abstractions in programming languages hide the internal representation of common data values in a computer. For example, integer data values are often stored in a computer using a two’s complement representation. On some machines, the integer value -64 is an abstraction of the 16-bit twos complement value 1111111111000000. Similarly, a real or floating-point data value is usually provided, which hides

the IEEE single- or double-precision machine representation of such numbers. These values are also called “primitive” or “atomic,” because the programmer cannot normally access the component parts or bits of their internal representation .

Another basic data abstraction is the use of symbolic names to hide locations in computer memory that contain data values. Such named locations are called variables. The kind of data value is also given a name and is called a data type. Data types of basic data values are usually given names that are variations of their corresponding mathematical values, such as int, double, and float. Variables are given names and data types using a declaration, such as the Pascal:

var x : integer;

or the equivalent C declaration:

int x;

In this example, x is established as the name of a variable and is given the data type integer.

3.2 Data: Structured Abstractions


The data structure is the principal method for collecting related data values into a single unit. For example, an employee record may consist of a name, address, phone number, and salary, each of which may be a different data type, but together represent the employee’s information as a whole.

Another example is that of a group of items, all of which have the same data type and which need to be kept together for purposes of sorting or searching. A typical data structure provided by programming languages is the array, which collects data into a sequence of individually indexed items. Variables can name a data structure in a declaration, as in the C:


int a[10];

which establishes the variable a as the name of an array of ten integer values.

3.3 Data: Unit Abstractions


In a large program, it is useful and even necessary to group related data and operations on these data together, either in separate files or in separate language structures within a file. Typically, such abstractions include access conventions and restrictions that support information hiding. These mechanisms

vary widely from language to language, but they allow the programmer to define new data types (data and operations) that hide information in much the same manner as the basic data types of the language.Thus, the unit abstraction is often associated with the concept of an abstract data type, broadly

defined as a set of data values and the operations on those values. Its main characteristic is the separation of an interface (the set of operations available to the user) from its implementation (the internal representation of data values and operations). Examples of large-scale unit abstractions include the module of Python and Java. Another, smaller-scale example of a unit abstraction is the class mechanism of object-oriented languages .

An additional property of a unit data abstraction that has become increasingly important is its reusability—the ability to reuse the data abstraction in different programs, thus saving the cost of writing abstractions from scratch for each program see figure 3.


3.4 Control: Basic Abstractions

Typical basic control abstractions are those statements in a language that combine a few machine instructions into an abstract statement that is easier to understand than the machine instructions. We have already mentioned the algebraic notation of the arithmetic and assignment expressions, as, for example:

SUM = FIRST + SECOND

This code fetches the values of the variables FIRST and SECOND, adds these values, and stores the result in the location named by SUM. The term syntactic sugar is used to refer to any mechanism that allows the programmer to replace a complex notation with a simpler, shorthand notation. For example, the extended assignment operation x += 10 is shorthand for the equivalent but slightly more complex expression x = x + 10, in C, Java, and Python.




3.5 Control: Structured Abstractions

Structured control abstractions divide a program into groups of instructions that are nested within tests that govern their execution. They, thus, help the programmer to express the logic of the primary control structures of sequencing, selection, and iteration (loops). At the machine level, the processor executes

a sequence of instructions simply by advancing a program counter through the instructions’ memory addresses. Selection and iteration are accomplished by the use of branch instructions to memory locations other than the next one.
3.6 Control: Unit Abstractions

Control can also be abstracted to include a collection of procedures that provide logically related services to other parts of a program and that form a unit, or stand-alone, part of the program. For example, a data management program may require the computation of statistical indices for stored data, such as mean, median, and standard deviation. The procedures that provide these operations can be collected into a program unit that can be translated separately and used by other parts of the program through a carefully controlled interface. This allows the program to be understood as a whole without needing to know the details of the services provided by the unit.


4. Language Definition

Language definition can be loosely divided into two parts: syntax, or structure, and semantics, or meaning. We discuss each of these categories in turn.


4.1 Language Syntax
The syntax of a programming language is in many ways like the grammar of a natural language. It is the description of the ways different parts of the language may be combined to form phrases and, ultimately,sentences. As an example, the syntax of the if statement in C may be described in words as follows:

PROPERTY: An if statement consists of the word “if” followed by an expression inside parentheses, followed by a statement, followed by an optional else part consisting of the word “else” and another statement.


The description of language syntax is one of the areas where formal definitions have gained acceptance,

and the syntax of all languages is now given using a grammar. For example, a grammar rule for

the C if statement can be written as follows:

::= if ()

[else ]

or (using special characters and formatting):

if-statement → if (expression) statement

[else statement]
4.2 Language Semantics

Syntax represents only the surface structure of a language and, thus, is only a small part of a language definition. The semantics, or meaning, of a language is much more complex and difficult to describe precisely. The first difficulty is that “meaning” can be defined in many different ways. Typically, describing the meaning of a piece of code involves describing the effects of executing the code, but there is no standard way to do this. Moreover, the meaning of a particular mechanism may involve interactions with other mechanisms in the language, so that a comprehensive description of its meaning in all contexts may become extremely complex.



4. Source program versus Execution


All high level languages are passed by three stages to be ready for execution. These levels are:

ويمر البرنامج المكتوب بلغات المستوى العالي بثلاث مراحل قبل أن يكون جاهزاً للتنفيذ وهى:

1- الترجمة Translation : وهو تحويل البرنامج المكتوب بلغة المستوى العالي إلى لغة الآلة الصفر و الواحد سواء باستخدام ما يسمى بالمترجم Compiler أو المفسر Interpreter.

2ـ الربط Linking : ربط الروتينات المكتبية الكائنة بالمكتبة، والتعليمات الضرورية بالبرنامج.

3ـ التحميل Loading : يقوم نظام التشغيل بتحميل شفرة الهدف والروتينات المكتبية، والتعليمات على الذاكرة الرئيسة بغرض التنفيذ .



1-4 Programming Languages Concepts مفاهيم لغات البرمجة

1-Data: are facts in raw or unorganized form (such as alphabets, numbers, or symbols) that refer to, or represent, conditions, ideas, or objects.

 

البيانات: Data : هى مجموعة من الأفكار و الحقائق التي تقوم بوصف شيء أو حدث دون القيام بمعالجة حسابية أو منطقية.

2- Information is processed data that is (1) accurate and timely, (2) specific and organized for a purpose, (3) can lead to an increase in understanding and decrease in uncertainty.
المعلومات: Information :هي مجموعة البيانات بعد المعالجة، أي أن البيانات هي المادة الخام للمعلومات أو أن المعلومات هي مجموعة الأفكار و الحقائق التي تصف شيء أو حدث ما بعد أن تمت معالجة الأفكار و الحقائق حسابياً أو منطقياً.

3- A database : is a collection of related information organized for rapid search and retrieval.

قاعدة البيانات Data Base:: و هي مجموعة ملفات البيانات الموجودة في أنظمة المعلومات دون تكرار.



4- File : A set of related records in a database

الملفات: Files : هى مجموعة من عناصر البيانات المتجانسة ذات علاقة واحدة مرتبطة بوصف مجموعة من الأشياء.



5- Record : A collection of related field and entries.

السجلات: Records : مجموعة من حقول البيانات تصف مجموعة من الحقائق عن شيء ما



6- Fields :group of characters or symbols for the details describing each record. Example: Name, address, and phone number would be fields .

A field is a column in the database. A record is a row in database.

الحقل: Field : مجموعة من الحروف أو الرموز التي تصف حقيقة واحدة لشيء ما.

الحروف أو الرموز: Characters or Symbols : مجموعة من الخلايا الثنائية تصف أحد الأحرف الأبجدية أو أحد الأرقام أو أي رمز خاص كإشارة +، _/* وغيرها. وهو ما يسمى بتمثيل الحروف والأرقام والرموز بالحاسب الآلى.

7- A computer program (also software, or just a program or application) is a sequence of instructions written to perform a specified task with a computer. The program has an executable form that the computer can use directly to execute the instructions.

البرنامج: Program :هو عبارة عن مجموعة من الأوامر مكتوبة بلغة محددة، بحيث تكون مرتبة ترتيباً منطقياً، موجهة لحل مشكلة محددة.

الأوامر: Instructions : تعليمات محددة المعنى تقوم بعمليات معالجة البيانات بحيث لا تتغير أشكال هذه التعليمات في اللغة الواحدة. وتختلف هذه الأوامر من لغة إلى أخرى.

Computer source code is often written by computer programmers. Source code is written in a programming language. Source code may be converted into an executable file (sometimes called an executable program or a binary) by a compiler and later executed by a central processing unit. Alternatively, computer programs may be executed with the aid of an interpreter.
البرنامج المصدري :Source Program هو البرنامج المكتوب باللغة التي يفهمها الإنسان.

البرنامج الهدفي :Target Program هو البرنامج المكتوب بلغة الآلة.

لغة الآلة :Machine Languageو هي عبارة عن لغة البرمجة التي كتبت تعليماتها بالشفرة الثنائية.

Compiler: is a group of software programs that are used to convert the source program to object program.(H.L.L to L.L.L) • المترجم Compiler :البرنامج الذي يقوم بعملية تحويل البرنامج المصدري إلى برنامج هدفي، بحيث تشمل عملية الترجمة ثلاثة مراحل رئيسة:

1. مرحلة التحليل: Analysis Phase وتتكون من ثلاث مراحل.

2. توليد شيفرة وسيطة: Intermediate Code Generation وتتكون من مرحلة واحدة.

3. توليد شيفرة ثنائية Code Generation وتتكون من مرحلتين.


و بالنسبة للمترجم فإن البرنامج المصدري تتم عملية الترجمة له جميعه دفعة واحدة بحيث ينتج عنه برنامج هدفي و يصدر أيضاً رسالة تحذيرية إذا كان هناك في البرنامج أي أخطاء.

المفسر :Interpreter فإن البرنامج المصدري تتم عملية الترجمة له سطراً سطراً، أى أن كل تعليمة من تعليمات البرنامج المصدري يقوم المفسر بتنفيذها تعليمة تلو الأخرى .

The interpreter execute the program line by line, while compiler convert all program as one patch to object program, then linking and finally loading (i.e Allocating in the memory with executable addresses)

أنواع برامج الترجمة1-5 Types of Translating Programs

There are three types of programs that are used to translate the source program to object programs. These are : Compiler, Interpreter, and Assembler.



1- المفسر: Interpreter و هو عبارة عن برنامج يعمل على تنفيذ البرنامج المصدري جملة تلو الجملة حيث ينفذ الجملة ثم ينتقل لتنفيذ الجملة التالية

. (Line by Line)



برنامج المصدر

جملة قابلة للتنفيذ

المفسر

الأخطاء
الشكل (1) آلية عمل المفسر



 

2- المترجم العالي Compiler: يستخدم المترجم العالي كبرنامج لترجمة البرامج المكتوبة بلغات البرمجة عالية المستوى و يحولها دفعة واحدة إلى برنامج تنفيذي. و يبين الشكل (2 ) آلية عمل المترجم العالي:

برنامج المصدر

البرنامج الهدفى

المترجم

قائمة الأخطاء

البرنامج التنفيذى

الشكل ( 2 ) آلية عمل المترجم العالي









3. المجمع :Assembler و يعمل بنفس الطريقة التي يعمل بها المترجم العالي إلاّ أنه يخصص لترجمة البرامج المكتوبة بلغة برمجة متدنية المستوى كلغة التجميع و يبين الشكل (3 ) آلية عمل المجمع:

برنامج التجميع

البرنامج الهدفى

المجمع

قائمة الأخطاء

البرنامج التنفيذى





الشكل (3 ) آلية عمل المجمع





2. Efficiency

Language designers nearly always claim that their new languages support efficient programs, but what does that really mean? Language designers usually think of the efficiency of the target code first.

That is, they strive for a language design that allows a translator to generate efficient executable code.

For example, a designer interested in efficient executable code might focus on statically typed variables,because the data type of such a variable need not be checked at runtime. Consider the following Java code segment, which declares and initializes the variables i and s and then uses them in later

computations.
int i = 10;

String s = "My information";

// Do something with i and s

Because the data types of these two variables are known at compile time, the compiler can guarantee

that only integer and string operations will be performed on them. Thus, the runtime system need not

pause to check the types of these values before executing the operations.

In contrast, the equivalent code in Python simply assigns values to typeless variables:
i = 10

s = "My information"

# Do something with i and s
The absence of a type specification at compile time forces the runtime system to check the type of a

Python variable’s value before executing any operations on it. This causes execution to proceed more

slowly than it would if the language were statically typed.

Another view of efficiency is programmer efficiency: How quickly and easily can a person read and write a program in a particular language? A programmer’s efficiency is greatly affected by a language’s expressiveness: How easy is it to express complex processes and structures?

The conciseness of the syntax also contributes to a language’s programming efficiency. Languages that require a complex syntax are often considered less efficient in this regard. For designers especially concerned with programmer efficiency, Python is an ideal language. Its syntax is extremely concise. For

example, unlike most languages, which use statement terminators such as the semicolon and block delimiters

such as the curly braces in control statements, Python uses just indentation and the colon. Figure 2.1 shows equivalent multiway if statements in Python and C to illustrate this difference

C Python

if (x > 0){ if x > 0.0:

numSolns = 2; numSolns = 2

r1 = sqrt (x); r1 = sqrt(x)

r2 = - r1; r2 = -r1

} elif x = 0.0:

else if (x == 0){ numSolns = 1

numSolns = 1; r1 = 0.0

r1 = 0.0; else:

} numSolns = 0

else

numSolns = 0;



Figure 2.1 Comparing the syntax of multiway if statements in C and Python
3. Regularity

Often regularity is subdivided into three concepts that are more well-defined: generality, orthogonal design, and uniformity



3.1 Generality

A language with generality avoids special cases wherever possible. The following examples illustrate this point.



Procedures and functions Function and procedure definitions can be nested in other function and procedure definitions in Pascal. They can also be passed as parameters to other functions and procedures. However, Pascal functions and procedures cannot be assigned to variables or stored in data structures. In

C, one can create pointers to functions to treat them as data, but one cannot nest function definitions. By contrast, Python and most functional languages, such as Scheme and Haskell, have a completely general way of treating functions (nested functions definitions and functions as first-class data objects).



Operators In C, two structures or arrays cannot be directly compared using the equality operator ==, but must be compared element by element. Thus, the equality operator lacks generality. This restriction has been removed in Smalltalk, Ada, Python, and (partially) in C++ and Java.
3.2 Orthogonality

In a language that is truly orthogonal, language constructs do not behave differently in different contexts.Thus, restrictions that are context dependent are considered nonorthogonal, while restrictions that apply regardless of context exhibit a mere lack of generality. Here are some examples of lack of orthogonality:



Placement of variable declarations In C, local variables can only be defined at the beginning of a block (compound statement),1 while in C++ variable definitions can occur at any point inside a block (but, of course, before any uses).
3.3 Uniformity

The term uniformity refers to the consistency of appearance and behavior of language constructs.

A language is uniform when similar things look similar or behave in a similar manner, but lacks uniformity when dissimilar things actually look similar or behave similarly when they should not. Here are some examples of the lack of uniformity. The extra semicolon In C++, a semicolon is necessary after a class definition, but forbidden after a function definition:

class A { ... } ; // semicolon required

int f () { ... } // semicolon forbidden

The reason the semicolon must appear after a class definition is that the programmer can include a list of

variable names before the semicolon, if so desired, as is the case with struct declarations in C.
4. Security

an exclusive focus on security can compromise both the expressiveness and conciseness of a language, and typically forces the programmer to laboriously specify as many things as possible in the actual code. Strong typing, whether static or dynamic, is only one component of safety. Several modern languages,such as Python, Lisp, and Java, go well beyond this and are considered to be semantically safe.

these languages prevent a programmer from compiling or executing any statements or expressions that violate the definition of the language. By contrast, languages such as C and C++ are not semantically safe. For example, an array index out of bounds error causes either a compile-time error or a runtime error in Python, Lisp, and Java, whereas the same error can go undetected in C and C++.

Likewise, in languages such as C and C++, the programmer’s failure to recycle dynamic storage can cause memory leaks, whereas in Python, Lisp, and Java, automatic garbage collection prevents this type of situation from ever occurring.


Extensibility

An extensible language allows the user to add features to it. Most languages are extensible at least to some degree. For example, almost all languages allow the programmer to define new data types and new operations (functions or procedures). Some languages allow the programmer to include these new

resources in a larger program unit, such as a package or module.

Very few languages allow the programmer to add new syntax and semantics to the language itself.

One example is LISP (see Graham [2002]). Not only can Lisp programmers add new functions, classes, data types, and packages to the base language, they can also extend Lisp’s syntax and semantics via a macro facility. A macro specifies the syntax of a piece of code that expands to other, standard Lisp code when the interpreter or compiler encounters the first piece of code in a program. The expanded code may then be evaluated according to new semantic rules. For example, Common Lisp includes a quite general do loop for iteration but no simple while loop. That’s no problem for the Lisp programmer, who simply

defines a macro that tells the interpreter what to do when it encounters a while loop in a program.

Specifically, the interpreter or compiler uses the macro to generate the code for an equivalent do loop wherever a while loop occurs in a program. Figure 2.2 shows LISP code segments for a do loop and an equivalent while loop that compute the greatest common divisor of two integers a and b.

(do () (while (> b 0)

((= 0 b)) (let ((temp b))

(let ((temp b)) (setf b (mod a b))

(setf b (mod a b)) (setf a temp)))

(setf a temp)))

Figure 2.2 A Lisp do loop and a Lisp while loop for computing the greatest common divisor of a and b

Figure 2.3 shows the code for a macro definition that would enable Lisp to translate a while loop to an equivalent do loop.



Figure 2.3 A Lisp macro that defines how to translate a Lisp while loop to a Lisp do loop

(defmacro while (condition &rest body)

'(do ()


((not ,condition))

,@body))





Download 140.47 Kb.

Share with your friends:




The database is protected by copyright ©ua.originaldll.com 2024
send message

    Main page