programming language concepts, week #7

37

Upload: others

Post on 03-Feb-2022

5 views

Category:

Documents


0 download

TRANSCRIPT

Programming Language Concepts, Week #7

Peter G. Anderson,Computer Science Department

Rochester Institute of Technology,Rochester, New York

[email protected] http://www.cs.rit.edu/

April 24, 2005

AbstractArgument passing mechanisms. Parsing. Functional programming.

Orthogonality. Vi as an orthogonal system. J project assignment.

1

Call by Address vs. Call by In+Out

In is call by value. Out returns an answer.

How can the combination of the two differ from call by address?

Consider the following program.

call addersub( x, x, y, y ). . . .subroutine addersub( in out a, in out b, address c, address d )

a = a + 1b = b + 1c = c + 1d = d + 1return

2

Call by Name

Here is a program to evaluate 13 + 23 + · · ·+ 1003.

All arguments are call by name.

y = addup( I, 1, 100, 1, I^3 ). . . .function addup( index, low, high, step, expression )

addup = 0index = lowwhile index <= high do

addup = addup + expressionindex = index + step

end whilereturn

3

Phrase Structure Grammars

A grammar is a system, G = (N,Σ, P, S)

A grammar defines a language, L(G) ⊂ Σ∗

The elements of L(G) are “sentences”

V = N ∪ Σ is the vocabularyΣ is the terminal vocabularyN is non-terminal vocabulary, the set of phrase names

P ⊂ N × V ∗ is the set of productions (rules)

S ∈ N is the sentence starter symbol

4

Derivations

The productions are written like this: A → α

If β, γ ∈ V ∗ and A → α ∈ P then we can apply a rewriting:

βAγ ⇒ βαγ

If xi ∈ V ∗, and xi ⇒ xi+1, for 0 ≤ i < n, then we say x0 derives xn:

x0∗⇒ xn

5

The Language of a Grammar

L(G) = {x ∈ Σ∗ | S∗⇒ x}

If S∗⇒ α for α ∈ V ∗ call α a sentential form

α is not a sentence unless α ∈ Σ∗

6

Left and Right Derivations

Left rule: Always rewrite the left-most element of N .

Right rule: Always rewrite the right-most element of N .

A grammar is ambiguous if some sentence has two different left (orright) derivations.

7

Right Parsing Parenthesis

The grammarS → () | (S) | SShas a sentence (()()).A shift-reduce parsing movie follows.The lines read in reverse order give aright derivation of the sentence.

stack input actionε ( ( ) ( ) )( ( ) ( ) ) shift

( ( ) ( ) ) shift( ( ) ( ) ) shift( S ( ) ) reduce 1

( S( ) ) shift( S( ) ) shift( S S ) reduce 1

( S ) reduce 3( S ) ε shift

S ε reduce 2

8

Left Parsing — aka Predictive Parsing

Use the grammarS → (S)S | εto parse (()()).We reverse the notion of the“top of stack.”The stack predicts the input.

input stack action

( ( ) ( ) ) S starting

( ( ) ( ) ) ( S ) S expand #1

( ) ( ) ) S ) S cancel (

( ) ( ) ) ( S ) S ) S expand #1

) ( ) ) S ) S ) S cancel (

) ( ) ) ) S ) S expand #2

( ) ) S ) S cancel )

( ) ) ( S ) S ) S expand #1

) ) S ) S ) S cancel (

) ) ) S ) S expand #2

) S ) S cancel )

) ) S expand #2

ε S cancel )

ε ε expand #2)

9

The Functional Paradigm

Consider two forms for summing an array:

function summer(low, high, A)

i = lowwhile i <= high do

summer = summer + A[i]i = i + 1

end whilereturn( summer )

function summer(low, high, A)

if low > high thenreturn( 0 )

elsereturn(A[low] + summer(low+1, high, A))

10

Imperative vs. Functional

Imperative programming ischaracterized by updating localstates (variables), creating sideeffects, using explicit loops.Languages:

• Fortran

• C, bc

• Snobol

Functional programming defines andevaluates functions. Functionalprogramming eschews variables.Languages:

• APL

• J

• Lisp, Scheme

But, you can use a functional programming style with any language.

11

Functions are “First Class Objects”

Functional programming languages provide the proper primitive functionsand operators to define functions.

12

Primitive Functions (Examples form J)

Constant functions: 0: 1: 2:, etc.

Identity functions: [ and ]

Primitive operations on scalar data: + - * ^ % < >, etc.

Primitive operations on aggregate data (e.g. lists, tables):# $ , |. |: { {. {:, etc.

13

Operators Create New Functions from Old Ones

Binding (aka Currying): &

Function composition: trains (hooks and forks), @ @: &.

Power: ^:

Rank application: "

Operators: commute ~, reflex ~, reduce /, prefix \

Inverse: ^:_1

Derivative: D.

14

Orthogonality

Features in a system are orthogonal if they do not interfere or poserestrictions on each other.

Orthogonality in a programming language makes it easier to learn.

15

Examples of Non-Orthogonality

Fortran’s DO-loop

DO 123 I = a,b,c...body...

123 ...last line of body

The initial, last, and step (a b c)must be integer constants orvariables—not expressions.

Fortran’s subscripts

A(I) = B(5)C(6*K) = D(L+7)E(3*M-2) = F(N-8)G(7*I+9) = X

The forms shown are the richestexpressions allowed (in Fortran IV,1965-1975).

16

PL/I’s Solutions: Allow Everything (From FAQ)

PL/I came into being as a result of an attempt to produce a revision ofFORTRAN. Such were the changes necessary that it was not possible tointroduce the new features needed to bring FORTRAN up-to-date, and tobe compatible with existing programs, that it was decided to introduce anew language that incorporated the best features of the then mainlanguages FORTRAN, COBOL, and Algol.

Originally, the language was called “New Programming Language,” orNPL. However, as these initials were already taken by the National PhysicsLaboratory in Britain, the name became PL/I.

PL/I contained features not seen before in a general-purpose programminglanguage—interrupt handling, array operations, list processing, and amacro pre-processor.

17

PL/I’s DO Loop

do i = 1 to 10; . . . end;do K = 1 to 10, 9 to 1 by -1; . . . end;do K = 9 to 1 by -1, 2 repeat 2*I while (I <= 1024); . . . end;do N = 1, 2, 3, 5, 7, 9, 10, 20, 30, 40; . . . end;

do bug = 1 to 10, bug = 20 to 100 by 10; . . . end;

The final example is an example of PL/I pornography.

18

Non-Orthogonality in Pascal’s read/write

read( a, b, c );read( a, b, c, d, e );

writeln( a, b, c );writeln( a, b, c, d, e );

But a programmer could not create a procedure with a variable number ofparameters.

C did allow that function, but without checking. How can you consume aparameter list?

19

Matrix Languages Operations

If ~x and ~y are two (column) vectors in N -space, linear algebra recognizesthe following operations:

1. Sum: ~z = ~x + ~yzi = xi + yi for 0 ≤ i < N

2. Inner (scalar, dot) product: a = ~x′ · ~ya =

∑N−1i=0 xi · yi

3. Outer product: M = ~x · ~y′Mij = xi · yj (The vectors ~x and ~y can be different sizes here.)

20

Matrix Languages Operations

Matrix languages support vector addition (and other component-wiseoperations: - * / <, etc.), inner and outer products.

They also support matrix multiplication: A = B · Cwhere Aij =

∑N−1k=0 Bik · Ckj

But they do not often allow us to replace the operators with otheroperators.

1. Outer products could be any-operation function tables.

2. Graph theory operations require and/or in place of times/plus in matrixmultiplication.

21

Early APL’s Non-Orthogonality

APL is the forerunner of J.

The reduction operationf/listonly allowed f to be a built-in verb:+ = * %, etc. f could not be aprogrammer-written verb.

J allows full generality here.

22

J’s Orthogonality

The reduction adverb “/” can be used with any verb.

The table adverb “/” can be used with any verb(recall our use of the verb “|” (remainder) in the prime numbers example).

Matrix multiplication can be used with any operators.

mmult =. +/ . *(B mmult C); (B =. i. 3 3); (C =. <:/~ i. 3)

+-------+-----+-----+|0 1 3|0 1 2|1 1 1||3 7 12|3 4 5|0 1 1||6 13 21|6 7 8|0 0 1|+-------+-----+-----+

23

Paths in Graphs

A symmetric 0–1 N ×N matrix is the adjacency matrix of a graphG = (V,E), where ||V || = N , and (i, j) ∈ E ⇔ Aij = 1.

Create the adjacency matrix of a hexagon graph (G) and H, the graph ofG’s vertices that are two edges apart. (H is the Star of David.)

gmult =. +./ . *.(gmult~ G) ; (G =. ((1&=)+.(5&=)) | -/~ i.6)

+-----------+-----------+|1 0 1 0 1 0|0 1 0 0 0 1||0 1 0 1 0 1|1 0 1 0 0 0||1 0 1 0 1 0|0 1 0 1 0 0||0 1 0 1 0 1|0 0 1 0 1 0||1 0 1 0 1 0|0 0 0 1 0 1||0 1 0 1 0 1|1 0 0 0 1 0|+-----------+-----------+

24

More Paths in Graphs

The adjacency matrix for G, above, gave the set of paths of length 1. Setthe main diagonal of G to 1’s (paths of length 0). Then G2 (in the sense ofgmult) is the paths of length 0, 1, and 2.

(gmult~ G);( G =. ((1&=)+.(5&=)+.(0&=)) | -/~ i.6)+-----------+-----------+|1 1 1 0 1 1|1 1 0 0 0 1||1 1 1 1 0 1|1 1 1 0 0 0||1 1 1 1 1 0|0 1 1 1 0 0||0 1 1 1 1 1|0 0 1 1 1 0||1 0 1 1 1 1|0 0 0 1 1 1||1 1 0 1 1 1|1 0 0 0 1 1|+-----------+-----------+

25

J’s Right to Left Evaluation

J evaluates expressions right to left, so we needed the (gmult~ G) after(to the right of) ( G =. ..... But, we can print the pair of boxed arraysin the temporal order using ;~

(gmult~ G);~( G =. ((1&=)+.(5&=)+.(0&=)) | -/~ i.6)+-----------+-----------+|1 1 0 0 0 1|1 1 1 0 1 1||1 1 1 0 0 0|1 1 1 1 0 1||0 1 1 1 0 0|1 1 1 1 1 0||0 0 1 1 1 0|0 1 1 1 1 1||0 0 0 1 1 1|1 0 1 1 1 1||1 0 0 0 1 1|1 1 0 1 1 1|+-----------+-----------+

26

J Project Requirements!!! (1 of 2)

Determine the number of connected components in random connectedgraphs.

A random graph’s adjacency matrix is a 0–1, N ×N , symmetric, random

matrix, with 2p ·(

N2

)one’s. p is the probability the that an edge exists:

0 ≤ p ≤ 1.

Perform the experiment for a large number of matrices, a large number ofsizes N , and a large number of probabilities p.

27

J Project Requirements!!! (2 of 2)

For your random graphs, determine the length of the paths between v0 andv1. (If no path exists, you can call the length 0 or ∞.)

Display the results of your investigation using some convenient tool, suchas gnuplot, excel, or histograms constructed using J.

28

Vi Considered as an Orthogonal system

“I know vi well enough to hate it!”

“There is no organization, rhyme, or reason to the thing!”

Observation of orthogonality convicted me otherwise

29

Cursor Motions—You Must be Able to Move Around

1. % moves to a matchingparenthesis.

2. 1G moves to the top of the file

3. G moves to the bottom of the file

4. H moves to the top of the screen

5. L moves to the bottom of thescreen

6. $ moves to the end of the line

7. 0 moves to the beginning of theline

8. fx moves right to the next x onthe line

9. Fx moves left to the next x onthe line

10. tx moves right to the positionbefore the next x on the line

11. Tx moves left to the positionafter next x on the line

30

Operations: M, d, c, y, !

A large number of vi operations are of the form

[”a]

dcy!

Msome textesc.

“dM” deletes the information in the path of M

You can delete the body of a C procedure by putting the cursor on the {and invoking d%

31

Changing Text

To change the text from the cursor to the end, type:c$some textesc.

To change from where you are to the bottom of the screen:cLsome textesc.

To change the whole file:1GcGsome textesc.

32

Buffers

Material that is deleted or changed can be recovered from the anonymousbuffer using the commands p or P.

You can place the deleted or changed material into one of the 26 namedbuffers by something like this:"adGThen dump it back into the file using:”ap or ”aP.

33

Yanking

Changing and deleting are destructive ways to get material into a buffer.

You can “yank” material over cursor motion using:["a]yM

34

Using Any Editing Function

The little filtering tools Unix has are generally for text editing: awk, sed,grep, egrep, bc, tr, head, tail, rev, tac, etc.

You can send several lines from your vi buffer into one of these filters (or afilter of your own writing) using !

!G sort!L bash!% bc!H tr a-z A-Z

End the lines with esc. or return

35

Shortcut Operations: cc, dd, yy, !!

To delete a line, type dd

To delete 3 lines, type 3dd

To yank 3 lines, type 3yy

To change 3 lines, type 3ccnew materialesc.

To compute a line, type !! bc(You can have a poor man’s spreadsheet.)

All these operation can be prepended with a buffer ”a

36