Principles of Programming Languages and Systems

by
Peter Fritzson,
PELAB - Programming Environment Laboratory
Dept. of Computer and Information Science,
Linköping University, Sweden

Lecture 1

Control abstractions

Basic abstractions (p 6)

Assignment statement

x = 555
[Graphics:lecture1gr2.gif][Graphics:lecture1gr1.gif]

x = x+300
[Graphics:lecture1gr2.gif][Graphics:lecture1gr3.gif]
Structured abstractions (p 7-9)

If-statement

If[x>800,
numSolns = 2;
Print["hejsan"]
,
numSolns=4;
Print["hoppsan"]
]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr4.gif]

While-statement

n = 9; 
While[n != 0,
Print[n];
n = Floor[n/2]
]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr5.gif]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr6.gif]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr7.gif]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr8.gif]

For-loop

For[i=1, i < 4, i++,
Print[i]
]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr9.gif]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr10.gif]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr11.gif]
Functional programming (p 12-14)

Conventional function style (p 13)

gcd[u_,v_] := Block[{
},
If[v==0,
Return[u]
,
Return[gcd[v,Mod[u,v]]]
]
];

gcd[8,18]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr12.gif]

Shorter version (Scheme-like, p 13)

gcd[u_,v_] := 
If[v==0,
u
,
gcd[v, Mod[u,v]]
];

gcd[8,16]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr13.gif]

Rule version (p 14)
(recurrence equations)

gcd[u_,0]  := u;

gcd[u_,v_] := gcd[v, Mod[u,v]];

gcd[8,28]
[Graphics:lecture1gr2.gif][Graphics:lecture1gr14.gif]

BNF and Abstract Syntax

Simple BNF grammar (p 70)

2-rule grammar

expr-- > expr + expr |
number
Abstract syntax intermediate form (p 72-73)

Textual input form, evaluated value

3 + 4 * 5
[Graphics:lecture1gr2.gif][Graphics:lecture1gr15.gif]

Abstract syntax intermediate form
(Hold prevents evaluation)

Hold[3 + 4 * 5] //FullForm
[Graphics:lecture1gr2.gif][Graphics:lecture1gr16.gif]