








































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









































pascal
small subset
why
Program file for this chapter:
This chapter and the next are about two related things: why different programming languages are different and how a programming language is implemented. To make the discussion concrete, I’ve chosen a specific language as an example: Pascal. That choice seems appropriate partly because Pascal is very different from Logo and partly because it is widely used as a vehicle for teaching introductory computer science, the same task I’m attempting in this book using Logo.*
For the purposes of this book I’ve written a program that translates a of Pascal into a simulated machine language. You can get a real Pascal compiler for your computer that accepts the full language, and that’s what you should do if you want to learn how to program in Pascal. I had two reasons for writing this subset compiler. One is that some readers may not otherwise have access to a Pascal compiler, and mine, despite its limitations, will enable you to explore the parts of the language I’m going to be talking about. The other is that the next chapter is about how a compiler works, and this compiler is accessible to examination because it’s written in Logo.
When you’re comparing two programming languages an obvious question to ask is “which is better?” Please don’t use my partial Pascal compiler as the basis for an answer to that question; it wouldn’t be fair. You already know my opinion, but my purpose in this chapter is not to convince you of it. Instead I want you to understand each
:n
fact
for
programming paradigm
functional programming
sequential programming
162 Chapter 4 Programming Language Design
to fact :n if :n=0 [output 1] output :n (^) * fact :n- end
to fact.seq :n localmake "product 1 for [i 1 :n] [make "product (:product * :i)] output :product end
language is designed the way it is. For each of the language differences we’ll examine, there are good reasons for either choice; the reasons that influence a language designer will depend on the overall goals he or she has for this language.
Perhaps the most important aspect of the design of a programming language is the that it encourages. A paradigm (it’s pronounced “para” as in “parakeet” followed by “dime” as in ten cents) is an approach to organizing a complex program: How do you combine the primitives of a language to accomplish harder tasks? It’s an aspect of programming style, but when people say “style” they’re usually thinking of smaller details, such as the use of comments in procedure definitions or choosing sensible variable names. Perhaps an example of different paradigms will help.
Here’s how the factorial function is usually computed in Logo, using a recursive operation:
The goal is to multiply several numbers together, the integers from 1 to. We do this by carrying out one multiplication in each recursive invocation. This procedure is written in the paradigm; the main tool for building up complexity is composition of functions. In this example, the result of the recursive invocation is composed with the primitive (multiplication) function.
Now consider this alternate approach:
This is an example of the paradigm, so called because the instruction carries out a sequence of steps:
Multiply the accumulated product by 1. Multiply the product by 2. Multiply it by 3.
−
n
i
1
=
f
choose
f n
n i
f i n >
n
f
f
164 Chapter 4 Programming Language Design
to simplex :buttons output 2 * f :buttons end
to f :n if equalp :n 0 [output 1] output cascade :n [? + ((choose :n (#-1)) * f (#-1))] 0 end
to simplex :buttons output 2 * first (cascade :buttons [fput (sumprods butfirst ?2 ?1) ?1] [1] [fput 1 nextrow ?2] [1 1]) end
to sumprods :a :b output reduce "sum (map "product :a :b) end
to nextrow :combs if emptyp butfirst :combs [output :combs] output fput (sum first :combs first butfirst :combs) ~ nextrow butfirst :combs end
Here’s a more complicated example, showing how data aggregates are used in the two paradigms. In Chapter 2 we explored the Simplex lock problem by computing the function
( ), if 0;
1, if = 0.
using these procedures:
Here, the mathematical definition of in terms of itself is reflected in the recursive nature of the operation. In Chapter 3, we improved the efficiency of the procedure by remembering smaller values of to avoid recomputing them; similarly, instead of computing the function separately each time, we used old values to compute new ones:
f
f f f f x f
f f
f
f f
Programming paradigms 165
cascade cascade
cascade map reduce
f combs
f combs for
for sumprods simplex
to simplex.seq :buttons localmake "f (array :buttons+1 0) localmake "combs (array :buttons+1 0) local [left right] setitem 0 :f 1 setitem 0 :combs 1 for [i 1 :buttons] [ setitem :i :f 0 make "right 0 for [j 0 :i-1] [ make "left :right make "right item :j :combs setitem :j :combs :left+:right setitem :i :f (item :i :f) + (item :j :f)*(item :j :combs) ] setitem :i :combs 1 ] output 2 * item :buttons :f end
The recursive nature of is less obvious in the second implementation, but the overall technique is still composition of functions. (Recall that the job of is to invoke a function repeatedly, in the pattern ( ( ( ( )))). In this case, is computing two functions in parallel; one is a list of values of the Simplex function and the other is a row of Pascal’s triangle.) The availability of higher order functions (in this program I’ve used , , and ) is another way in which Logo encourages the functional paradigm.
In sequential style, the composition of functions is replaced by a sequence of steps in which values are stored in boxes (members of arrays) and repeatedly replaced with different values:
It may take some effort to convince yourself that this procedure really computes the same results as the other versions! Within the procedure, the array contains the values (0), (1),... as they are computed one by one; the array contains one row (at a time) of Pascal’s triangle.
The procedure first puts (0) into the zeroth position of the array and the first row of Pascal’s triangle (containing just one 1) in the array. Then comes a loop that computes (1), then (2), and so on, until the desired value is reached. An inner loop fills the same purpose as the function in the previous version of : It computes the sum of several terms, not by function composition but by adding each term into the sum separately. The instruction
map cascade
run apply for while do.until ifelse
make setitem .setfirst
object-oriented programming.
methods, variables,
message
Programming paradigms 167
list processing (you can create lists in Pascal, but it’s painful), and even more importantly because in Logo it’s easy to invent higher order functions such as and. Pascal programmers can’t readily invent their own control structures because there’s nothing like or in Pascal, and the built-in control structures are all sequential ones. (In addition to , Pascal has equivalents to the and commands in the Berkeley Logo library.) As another example, Logo’s primitive can be used either as a command or as an operation, but the Pascal equivalent works only as a command.
Not all programming languages compromise between paradigms. It’s rare these days to see a purely sequential language, but it used to be common; both the original Fortran language and the early microcomputer versions of BASIC lacked the ability to handle recursive procedures. Purely functional languages are not widely used in industry, but are of interest to many computer science researchers; the best known example is called ML. In a purely functional language, there is no assignment operator (like in Logo) and no mutators (like or ).
There are other programming paradigms besides sequential and functional, al- though those are the oldest. The sequential paradigm came first because the actual digital computer hardware works sequentially; Fortran, which was the first higher level programming language, was initially viewed as merely an abbreviation for the computer’s hardware instruction sequences.* The functional paradigm was introduced with Lisp, the second-oldest programming language still in use. Although Lisp is not a pure functional language (it does have assignment and mutation), its design is firmly based on the idea of functions as the way to express a computation.
Another paradigm that’s very popular today is In this paradigm, we imagine that instead of having a single computer carrying out a single program, the computational world includes many independent “objects,” each of which can carry out programs on its own. Each object includes which are like local procedures, and just like the variables we’ve used all along except that each belongs to a particular object. If one object wants to know the value of another object’s variable, the first object must send a to the second. A message is a request to carry out a method, so the messages that each object accepts depends on the methods that it knows.
forward
ask 7 [forward 100]
simulation
every
information hiding;
logic programming declarative programming.
168 Chapter 4 Programming Language Design
Logo has had a sort of glimmer of the object paradigm for many years, because many dialects of Logo include multiple turtles. To move a turtle, you send it a message, using a notation something like
to send a message to turtle number 7. But this notation, even though it conveys some of the flavor of object-oriented programming, is not truly representative of the paradigm. In a real object system, it would be possible for specific turtles to have their own, specialized methods. Turtle 7, for example, might be a special “dotted turtle” that draws dotted lines instead of solid lines when it moves forward. One Logo dialect, called Object Logo, does provide a genuine object capability.
Object-oriented programming fits naturally with the sort of problem in which the computer is modeling or simulating a bunch of real-world objects; in fact, the paradigm was invented for programs, used to try to answer questions such as “Will it eliminate the traffic jams if we add another lane to this highway, or should we spend the money on more frequent bus service instead?” The objects in the simulation program are people, cars, buses, and lanes. Another example of a problem that lends itself to the object paradigm is a window system, such as the one in Mac OS or in Microsoft Windows. Each window is an object; when a window is displayed so as to hide part of another window, the new window must send a message to the hidden one telling it not to display the hidden region.
Some people argue that object-oriented programming should be used for pro- gramming problem, not because the independent object metaphor is always appropriate but because using objects helps with if every variable belongs to a specific object, the program is less likely to have the kind of bug in which one part of a program messes up a data structure that’s used in another part. This can be particularly important, they say, in a large programming problem in which several programmers work on different pieces of the program. When the different programmers’ procedures are put together, conflicts can arise, but the object paradigm helps isolate each programmer’s work from the others. Although this argument has some merit, I’m cautious about any claim that one particular paradigm is best for all problems. I think programmers should be familiar with all of the major paradigms and be able to pick one according to the needs of each task.
Another important programming paradigm is called or In this approach, the programmer doesn’t provide an algorithm at all, but instead lists known facts about the problem and poses questions. It’s up to the language implementation to search out all the possible solutions to a question. We saw a very
tower
... and so on.
hanoi 5 "a "b "c
program name;
170 Chapter 4 Programming Language Design
To use these procedures you issue an instruction like
Here is the corresponding Pascal program. This program is in the file. (As you can see, Pascal programs begin with a in all of the examples in this chapter the file name is the same as the program name, although that isn’t a requirement of Pascal.) Never mind the program details for the moment; right now the point is to make sure you know how to get the Pascal compiler to translate it into Logo.
to hanoi :number :from :to :other if equalp :number 0 [stop] hanoi :number-1 :from :other :to movedisk :number :from :to hanoi :number-1 :other :to :from end
to movedisk :number :from :to print (sentence [Move disk] :number "from :from "to :to) end
? Move disk 1 from a to b Move disk 2 from a to c Move disk 1 from b to c Move disk 3 from a to b Move disk 1 from a to c
program tower; {This program solves the 5-disk tower of hanoi problem.}
procedure hanoi(number:integer;from,onto,other:char); {Recursive procedure that solves a subproblem of the original problem, moving some number of disks, not necessarily 5. To move n disks, it must get the topmost n-1 out of the way, move the nth to the target stack, then move the n-1 to the target stack.}
procedure movedisk(number:integer;from,onto:char); {This procedure moves one single disk. It assumes that the move is legal, i.e., the disk is at the top of its stack and the target stack has no smaller disks already. Procedure hanoi is responsible for making sure that’s all true.}
begin {movedisk} writeln(’Move disk ’,number:1,’ from ’,from,’ to ’,onto) end; {movedisk}
... and so on.
compile
prun program
compile "tower
prun "tower
source file
workspace,
Interactive and Non-interactive Languages 171
begin {hanoi} if number <> 0 then begin hanoi(number-1,from,other,onto); movedisk(number,from,onto); hanoi(number-1,other,onto,from) end end; {hanoi}
begin {main program} hanoi(5,’a’,’b’,’c’) end.
?
? Move disk 1 from a to b Move disk 2 from a to c Move disk 1 from b to c Move disk 3 from a to b Move disk 1 from a to c
Once you have a Pascal program in a disk file, you compile it using the command with the file name as input:
The compiler types out the program as it compiles it, partly to keep you from falling asleep while it’s working but also so that if the compiler detects an error in the program you’ll see where the error was found.
When the compiler has finished processing the (the file containing the Pascal program) it stops and you see a Logo prompt. At this point the program has been translated into a simulated machine language. To run the program, say
The input to the (Pascal run) command is the program name—the word that comes after at the beginning of the source file.
The difference between an interactive and a non-interactive language is not just an arbitrary choice of “user interface” style. This choice reflects a deeper distinction between two different ways of thinking about what a computer program is. In Logo there is really no such thing as a “program.” Each procedure is an entity on its own. You may think of one particular procedure as the top-level one, but Logo doesn’t know that; you could invoke any procedure directly by using an interactive instruction naming that procedure. Logo does have the idea of a a collection of procedures stored
run
hanoi
if for
intermediate
portable
why
Interactive and Non-interactive Languages 173
rather the one representing the Logo interpreter itself. If the procedure specialists are like circus performers, the Logo interpreter is the ringmaster. The circus metaphor is actually a pretty good one, because on the one hand each performer is an autonomous person, but at the same time the performers have to cooperate in order to put on a show. The relevance of the metaphor to this discussion is that in a compiled language there is no “ringmaster.” The compiler is more closely analogous to a bird that hatches an egg (your program) and then pushes the new bird out of the nest to fend for itself. In a compiled language there is no provision for an interactive interface to which you can give commands that control the running of your program, unless your program itself includes such an interface.
Saying the same thing in a different way, the Logo interpreter is part of the environment in which any Logo program operates. (That’s why Logo can provide a facility like the command to allow your program to construct new Logo instructions as it progresses.) But a Pascal compiler does its job, translating your program into another form, and then disappears. Whatever mechanisms are available to control your program have to be built into the program. For example, my Pascal version of the Tower of Hanoi program includes the top-level instruction that starts up the solution for five disks. In the Logo version, that instruction isn’t considered part of the program; instead, you direct Logo interactively to invoke the procedure.
The distinction between compiled and interpreted languages is not as absolute as it once was. There are versions of Logo in which each procedure is compiled as you define it, but it’s still possible to give instructions interactively. (Some such versions include both a compiler and an interpreter; in others, the “interpreter” just arranges to compile each instruction you type as if it were a one-line program.) And many current Pascal compilers don’t compile into the machine language of the host computer, but rather into an language called “P-code” that is then interpreted by another program, a P-code interpreter. P-code is called an intermediate language because the level of detail in a P-code program is in between that of a language you’d want to use and that of the underlying machine language. Its primitives are simple and quick, not complex control structures like or. The advantage of a Pascal language processor based on P-code is that the compiler is —it can work on any computer. All that’s needed to start using Pascal on a new computer is a P-code interpreter, which is a relatively easy programming project.
So far I’ve been explaining a language design decision (interactive or non-interactive development) in terms of an implementation constraint (interpreted or compiled). But it’s possible to look beyond that explanation to ask someone would choose to design a compiler rather than an interpreter or vice versa.
incremental
never
program specification
inside
174 Chapter 4 Programming Language Design
The main advantage of a compiler is that the finished object program runs fast, since it is directly executed in the native language of the host computer. (An interpreter, too, ultimately carries out the program in the computer’s native language. But the interpreter must decide which native language instructions to execute for a given source language instruction each time that instruction is evaluated. In a compiled language that translation process happens only once, producing an object program that requires no further translation while it’s running.) The tradeoff is that the compilation process itself is slow. If you’re writing a program that will be used every day forever, the compiled language has the advantage because the development process only happens once and then the program need not be recompiled. On the other hand, during program development the compiled language may be at a disadvantage, because any little change in one instruction requires that the entire program be recompiled. (For some languages there are compilers that can keep track of what part of the program you’ve changed and only recompile that part.)
A compiled language like Pascal (or Fortran or C), then, makes sense in a business setting where a program is written for practical use, generally using well-understood algorithms so that the development process should be straightforward. An interpreted language like Logo (or Lisp or BASIC) makes more sense in a research facility where new algorithms are being explored and the development process may be quite lengthy, but the program may never be used in routine production. (In fact nobody uses BASIC for research purposes, because of other weaknesses, but its interactive nature is a plus.) Another environment in which interaction is important is education; a computer science student writes programs that may actually be run except for testing. The program is of interest only as long as it doesn’t work yet. For such programs the speed advantage of a compiled program is irrelevant.
There are also reasons that have nothing to do with implementation issues. I’ve spoken earlier of two conflicting views of computer science, which I’ve called the software engineering view and the artificial intelligence view. In the former, the program development process is seen as beginning with a clear, well-defined idea of what the program should do. This idea is written down as a that forms the basis for the actual programming. From that starting point, the program is developed top-down; first the main program is written in terms of subprocedures that are planned but not written yet; then the lower-level procedures are written to fill in the details. No procedure is written until it’s clear how that procedure fits into a specific overall program. Since Pascal’s developers are part of the software engineering camp, it’s not surprising that a Pascal program takes the form of an integrated whole in which each procedure must be a larger one, rather than a collection of more autonomous procedures. By contrast, Logo is a product of the artificial intelligence camp, for whom program
hanoi tower
a b i j
hanoi tower
movedisk begin end
v p
movedisk hanoi movedisk
program tower; var a,b:real; i,j:integer; procedure hanoi(number:integer;from,onto,other:char);
part of
same
mean local variable
formal parameters
actual arguments.
176 Chapter 4 Programming Language Design
declaration of the procedure , for example, is the program. This particular program uses no global variables, but if it did, those variables would also have to be declared within the program. If the program used global variables , , , and then it might begin
In summary, a Pascal program consists of
But notice that the procedure , declared inside , has the structure as the entire program. It begins with a header line; its declaration part includes the declaration of procedure ; it has a statement part between and ; its final punctuation is a semicolon instead of a period.
What does it for one procedure to be declared inside another? You already know what a means; if a variable belongs to a procedure then that variable exists only while the procedure is running; at another point in the program there might be a different variable with the same name. In Pascal, the same is true for local procedures. In our example program, the procedure exists only while procedure is running. It would be an error to try to invoke directly from the main program.
The header line for a procedure can include names for its inputs, just as the title line of a Logo procedure names its inputs. A useful bit of terminology is that the variable names in the procedure header are called to distinguish them from the expressions that provide particular input values when the procedure is actually invoked; the latter are called The words “parameter” and “argument” are both used for what we call an “input” in Logo.*
tower
begin end
to If true false true
statement statement statement
condition statement
block. block structured compound statements.
between
simple
Every
Statement Types 177
begin ; ; end
begin hanoi(number-1,from,other,onto); movedisk(number,from,onto); hanoi(number-1,other,onto,from) end
if then
the Pascal compiler doesn’t care about spacing and line breaks, people always do it as I’ve shown you here, with subordinate parts of the program indented and each statement on a separate line.
The sequence of header, declarations, statements, and punctuation is called a Pascal is called a language because of the way blocks can include smaller blocks. Another aspect of block structure is Pascal’s use of A sequence of the form
is called a compound statement. An example from the program is
(Notice that semicolons go statements within this sequence; none is needed after the last statement of the group. This syntactic rule is based on the analogy between Pascal statements and English clauses that I mentioned earlier.) For example, Pascal includes a conditional statement whose form is
The “statement” part can be a single statement, like a procedure call, or it can be a compound statement delimited by and. Because the general term “block structured language” refers to any syntactic grouping of smaller units into a larger one, including compound statements, you may hear the word “block” used to refer to a compound statement even though that’s not the official Pascal meaning.
In Logo we don’t talk about different kinds of statements like compound, simple, and so on. Logo instruction (well, all but ) is a procedure invocation. , for example, is a procedure whose first input is or and whose second input is a list containing instructions to be carried out if the first input is. In Pascal there are several different kinds of statements, each with its own syntax.
before
Statement Types 179
movedisk tower writeln
movedisk :
:x < 10 while if If if if true false While while true false
if while
number:
writeln(1,2,3,4); writeln(1000,2000,3000,4000);
1 2 3 4 1000 2000 3000 4000
if :x < 10 [increment "x] while [:x < 10] [increment "x]
Not only do they take a variable number of arguments, but the arguments can take a special form not ordinarily allowed. In the procedure in the program, one of the arguments to is
The “ ” here means “using one print position unless more are needed to fit the number.” Pascal print formatting is designed to emphasize the printing of numbers in columns, so the default is to print each number with a fairly large number of characters, with spaces at the left if the number doesn’t have enough digits. The exact number of characters depends on the type of number and the dialect of Pascal, but 10 is a typical number for integers. So
will give a result looking something like this:
In I had to say “ ” to avoid all that extra space.
What are the pros and cons of using a variety of syntax rules for different kinds of statements? One reason for the Pascal approach is that differences in meaning can be implicit in the definitions of different statement types instead of having to be made explicit in a program. Don’t worry; you’re not expected to understand what that sentence meant, but you will as soon as you see an example. In Logo we say
Why is the predicate expression in a quoted list in the case of but not for? wants the expression to be evaluated once, is invoked. The actual input to is not that expression but the value of the expression, either or
. , on the other hand, wants to evaluate that expression repeatedly. If Logo evaluated the expression ahead of time and gave an input of or it wouldn’t be able to know when to stop repeating.
The fact that wants the condition evaluated once but wants to evaluate it repeatedly has nothing to do with the syntax of Logo; the same is true in Pascal. But in Pascal you say
if while
if while
make
make
x
"x :x
semantic Syntax semantics
name value
180 Chapter 4 Programming Language Design
if x<10 then increment(x); while x<10 do increment(x);
make "new :old
new := old
x := x+
make "x :x+
In Logo the fact that ’s condition is evaluated in advance but ’s isn’t is made explicit by the use of square brackets. In Pascal it’s just part of the definitions of the and statements. ( is the form in which something is represented; is the meaning of that something.)
One more example: Beginning students of Logo often have trouble understanding why you say
to assign the value of one variable to another variable. Why is the first quoted and the second dotted? Of course you understand that it’s because the first input to is the of the variable you want to set, while the second is the that you want to give it. But in Pascal this distinction is implicit in the semantic definition of the assignment statement; you just say
Since beginning Logo students have trouble with quotes and dots in , you might think that the Pascal approach is better. But beginning Pascal students have a trouble of their own; they tend to get thrown by statements like
This doesn’t look quite as bad as the BASIC or Fortran version in which the symbol for assignment is just an equal sign, but it’s still easy to get confused because the symbol “ ” means two very different things in its two appearances here. In the Logo version
the explicit difference in appearance between and works to our advantage.
Which way do you find it easier to learn something: Do you want to start with a simple, perhaps partly inaccurate understanding and learn about the difficult special cases later, or do you prefer to be told the whole truth from the beginning? I’ve posed the question in a way that shows my own preference, I’m afraid, but there are many people with the opposite view.
The issue about whether or not to make the semantics of some action implicit in the syntax of the language is the most profound reason for the difference between Logo’s single instruction syntax and Pascal’s collection of statement types, but there are other