Академический Документы
Профессиональный Документы
Культура Документы
Fall 2007 Notes
1. Why Study
Choosing language to use, Easier to learn new languages,
Understand obscure features (e.g., .* in C++), Choose among
alternative ways to express things (e.g., x*x versus x^2 versus
x**2), Make good use of debuggers and assemblers and linkers
and related tools, Simulate features in languages that lack them
(e.g., iterators in Clu and Icon)
2. Environments
Tools – debuggers, assemblers, preprocessors, compilers,
linkers, style checkers, configuration management, software
engineering tools, tracers, breakpoints, steppers, windows – Visual
Studio and .Net
3. Interpretation
Compilers versus Interpreters, Hybrids
Fortran libraries and linker (link editor)
Intermediates – Assemblers, Preprocessors, Intermediate
code (e.g., P-code)
4. Compilers and Computing Theory
Scanner – lexical analysis, Parser – syntax analysis,
Semantic analysis – intermediate code generation, Machine-
independent code improvement (optional), Target code generation,
Machine-specific code improvement (optional); Symbol table
An Example Program
program gcd(input, output);
var i,j: integer
begin
read(i,j)
while i<>j do
if i>j then i := i - j
else j := j – 1;
writeln(i)
end.
Its Tokens (Lexemes)
program gcd ( input , output ) ;
var i , j : integer ; begin
read ( i , j ) ; while
i <> j do if i > j
then i := i - j else j
:= j - i ; writeln ( i
) end .
Grammar
program PROGRAM identifier ( identifier
more_identifiers): block .
where
block labels constants types variables
subroutines BEGIN statement
more_statements END
more_identifiers identifiers
more_identifiers | e e empty string
Programming Language Syntax
Precision
Rules (Production rules or productions)
digit 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
nonzerodigit 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
natural_number nonzerodigit digit*
Kleene star (meta-symbol meaning 0 or more
occurrences)
Chomsky grammars
(S,T,N,S) - S is alphabet, T is set of terminals (words), N is
set of nonterminals
(parts of speech), and S is an element of N and is
the start symbol
Rules – Concatenation, Alternation (choice among
alternatives – may use |),
Repetition (*)
Regular grammar – uses only those rules
Lexical analysis
Regular expressions: a character, empty string, two
regular expressions concatenated together, two regular
expressions in alternation (|), or a regular expression
followed by the Kleene star (*)
Context-free grammars – add recursion
Parsers
Context-sensitive grammars and General grammars
Theory
DFA = deterministic finite automaton
Q (finite set of states), (an alphabet of input symbols),
qQ (an initial state),
FQ (distinguished final states), and :QQ
(transition function)
NFA – transition function is multivalued – implies
guessing
Regular expressions
DPDA – deterministic pushdown automata – stack
Q, , q, F, (finite set of stack symbols), Z
Another Example - Tokens
digit 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
unsigned_integer digit digit*
unsigned_number unsigned_integer
((. unsigned_integer) | e)
((e (+|-|e) unsigned_integer) | e)
Another Example - Context-free Grammar
expression identifier | number | - expression |
( xpression ) |
expression operator expression
operator - | + | * | /
identifier_list identifier | identifier_list , identifier
Derivations and Parse Trees
Another Example: slope * x + intercept
expression expression
operator expression expression operator identifier
expression + identifier expression
operator expression + identifier
expression operator identifier + identifier
expression * identifier + identifier identifier *
identifier + identifier
slope * x + intercept
Ambiguity
Revised grammar
Precedence (*, / before +,-) Associativity – breaking
precedence ties
2^3^4 with ^ implying exponentiation
left (2^3)^4 = 8^4 = 2^12 =
4096 right 2^(3^4)
= 2^81
Scanning lexical analysis
Deterministic finite automaton (dfa) – recognizes tokens
Note: parser is a deterministic push-down automaton (dpa)
for context-free grammars
Pascal scanner
Finite automaton
Lexical errors
Comments (pragmas) – significant commands to compiler
Parsing
Top Down versus Bottom Up
LL – left to right scan, left-most derivation – top down
Manual or parser-generator construction
Predictive parsing
LL(k) – look ahead k tokens
Example
id_list id id_list_tail
id_list_tail , id id_list_tail | ;
Figure id(A), id(B), id(C)
Recursive Descent
$$ end pseudo-token
grammar
program stmt_list $$
stmt_list stmt stmt_list | e
stmt id := expr | read id | write expr
expr term term_tail
term_tail add_op term term_tail | e
term factor factor_tail
factor_tail mult_op factor factor_tail | e
factor ( expr ) | id | literal
add_op + | -
mult_op * | /
recursive descent program – (LL(1) parse)
read A
read B
sum := A + B
write sum
write sum / 2
parse tree
Errors
Panic mode, Phrase-level recovery, Context-sensitive
look-ahead,
Exception-based recovery, Error productions
Table-Driven Parsing
Predict sets
Writing Grammars
Ambiguity (e.g., dangling else)
LR – left to right scan, right-most derivation
SLR, LALR, full LR subclasses
Number of tokens for look-ahead (e.g., 1)
Stack
Semantic Analysis
Static – structural
Attribute grammars
Rule X0 X1 X2 … Xn
Parse tree:
X0
| | … |
X1 X2 … Xn
A(Xj) – some attribute of symbol Xj
Synthesized attributes – passed up parse tree
S(X0) =f(A(X1),f(X2)…A(Xn)
Intrinsic attributes - synthesized attribute for
leaf node
determined outside parse tree (e.g., type
from symbol table of a variable)
Inherited attributes – passed down parse tree
I(Xj) =f(A(X0),f(X1)…A(Xj-1)
Example Grammar
assign var expr
expr var + var | var
var A | B | C
actual_type – synthesized, intrinsic for a variable
expected_type – inherited, depends on left-hand-
side (lhs) of assignment statement
Dynamic – meaning
Operational – simulation on target machine
Example: C statement
for (expr1; expr2; expr3) { … }
Operational semantics
expr1;
loop: if expr2 = 0 goto out
…
expr3;
goto loop
out:
Axiomatic – proof of correctness (logic)
Assertions - logical predicates
Axiom – logical statement assumed to be true
Inference rule – method of inferring truth of one
assertion on the basis of other assertions
pre- and post- conditions
Px precondition defined by axiom P = QxE
P computed as Q with all instances of x
replaced by E
A=b/2–1 (a<10 postcondition)
– substitute b/2-1 in a<10 to get b<22
Sum = 2*x+1 {sum>1 postcondition }
{x>10 precondition}
but weakest precondition {x>0}
Sequences of statements
{P}S{Q}
{P}S{Q},P’P,QQ’/{P’}S{Q}
Logical pretest loops – loop invariants
While (y<>x) do y=y+1 end
{y=x precondition}
{y<=x loop invariant}
Kraft example: Linear Search
void function ls(list x, list_type key, k int
answer)
{
int i;
for (i=1; i<=length(x); i++)
if (key == x[i]) then {
return (i);
break
};
return(0)
}
loop invariant – ls returns index of first
occurrence of key or 0 if key not in list
Denotational - recursive function theory
bin_num 0 | 1 | bin_num 0 | bin_num 1
Mbin(x) = meaning of x
Mbin(‘0’)= 0, Mbin(‘1’)=1,
Mbin(bin_num ‘0’)=2*Mbin(bin_num),
Mbin(bin_num ‘1’)=2* Mbin(bin_num)+
Data Types
Type – set of values an entity can take
Declaration and Definition – Name of entity and name of type
Denotational – set of values
domain
Constructive – small collection of built-in types
(primitives or predefined -
e.g., Boolean, integer, character, real)
or composite (constructor, e.g.,
record, array, set)
Abstract (interface, set of operations, mutually consistent
semantics)
Boolean (logicals), characters, integers (unsigned integers called
cardinals)
Ordinals or discrete types
rationals, reals, complex numbers, decimals
ordinals and those immediately above – scalar or simple
Enumeration types
Type weekday = (sun,mon,tue,wed,thu,fri,sat);
Can be index types in Pascal
Subrange types
Type test_scores = 0..100;
Composites
Arrays, Sets, Files, Lists, Pointers
Orthogonality
Type Checking
Equivalence – same type
Compatility – operations allowed
Inference – type determined from constitutent parts of an
expression
Conversion (coercion)
Casts
Arrays
Addressing
Slices and Operations
Array Addressing
Unions (Variant records)
Sets
Pointers
References
Array Addressing
Let
c = the size of an element (ArrayElementType) in memory units
k = dimensionality of array (number of dimensions)
Consider
ArrayElementType b[L1:U1, … Lk:Uk];
Note
Lj Ij Uj
Nj= number of elements in array b along dimension j = Uj - Lj+ 1
N = number of elements in array b = j=1k Nj
Then
Address(b[I1, …, Ik]) = Address(b[L1, …, Lk]) + {c * factor}
For row-major order, storing and retrieving the first row, then the second
row, and so on, with the leftmost subscript moving the slowest going across
linear memory and the rightmost subscript moving the fastest, we have
factor = t=1k-1 (r=t+1k [Ur – Lr +1] (It – Lt)) + (Ik – Lk)
For column-major order, storing and retrieving the first column, then the
second column, and so on, with the rightmost subscript moving the slowest
going across linear memory and the leftmost subscript moving the fastest,
we have
factor = t=2k (r=1t-1 [Ur – Lr +1] (It – Lt)) + (I1 – L1)
Recursion and the Activation Record (and the Run-Time
Stack)
An Example for Factorials (n!, where n is a nonnegative integer) */
#include <stdio.h>
int facit(int);
int facrecur(int);
int facrecursim(int);
int stackparm[101]; int stackra[101];
int top = 0; /* run-time stack as array */
void main() {
int n;
printf (“input n, the factorial number desired as a
nonnegative
integer\n”); scanf(“%d”,&n);
printf (“iterative factorial %d = %d! = %d\n”, n, n, facit(n));
printf(“\n”);
printf (“recursive factorial %d = %d! = %d\n”, n, n,
facrecur(n)); printf(“\n”);
printf (“simulated recursive factorial %d = %d! = %d\n”, n,
n, facrecursim(n)); printf(“\n”);
}
int facit (int n) {
int i; int prod = 1;
for (i = n; i 1; i--) { prod *= i; }
return (prod);
}
int facrecur (int n) {
if (n == 0) return (1);
else return (n * facrecur(n-1));
}
/* Factorial Via Simulated Recursion
0. Initialize
a. Input integer n
b. parameter = n parameter is of type
integer
c. returnaddress := 0 switch - 0 main
program
d. create stack stack hold return-address
and parameter
e. top = 0 run-time stack initially
empty
1. push(parameter,returnaddress) (call)
2. If parameter = 0 then
a. factorial := 1
b. go to step 4
else
a. parameter := parameter –1
b. returnaddress = 3 switch – 0step 3
recursive caller
c. go to step 1
3. factorial := factorial * (parameter + 1)
4.
a. pop(parameter,returnaddress)
b. if returnaddress = 3 then go to step 3
c. else go to main program */
void push (int *parm, int *ra) {
top += 1;
stackparm[top] = *parm; stackra[top] = *ra;
}
void pop (int *parm, int *ra) {
*parm = stackparm[top]; *ra = stackra[top];
top -= 1;
}
int facrecursim (int n) {
int parm; int ra = 0; int step = 0; int fac;
parm = n;
while (step != 4) {
push (&parm, &ra);
if (parm == 0) { fac = 1; step = 4; }
else { parm -= 1; ra = 3; }
}
while (ra == 3) {
if (step != 4) fac *= (parm + 1);
pop(&parm, &ra); step = 0;
}
return (fac);
}
Lisp
S-expression (symbols)
Atom – x, 1, “a”
List – (a b c)
Sublists - (a (b c) (d (e (f g) h))) - sub
Evaluation – first element of list assumed to be an
operator, remainder are operands
- every operator is a function returning a value
- side effects – print, assignment
(+ 5 3) 8 (+ 3 5 9 11) 28 (* (+ 2 3) (+ 4
6)) 50
; comment
postponed (controlled) evaluation of symbols
Operators
exit, load, +, -, 1+, 1-, *, /
(set ‘x 4) or (setq x 4) ; assignment
quote
car,. cdr ; breakdown lists
(car ‘(a b c)) a (car (‘(a b) c d e)) (a b) ; head of list
(cdr ‘(a b c)) (b c) ; tail of
list (caaadddr)
cons, list, append ; put lists together
(cons Elem List) (Elem List)
(list Elem1 Elem2 … ElemN) (Elem1 Elem2 … ElemN)
(append List1 List2 … ListN) (elements of list arguments
in order)
(cons ‘a ‘(b c)) (a b c) (list ‘a ‘(b c) ‘d) (a (b c) d)
(append ‘(a b) ‘(c d) ‘(e f)) (a b c d e f)
car, cdr, cons, list, append not destructive
nil () ; empty list, also indicator of “false”
Functions (user defined)
(defun function-name (list of formal parameters)
(defun add3 (x) (+ x 3)) add3
formal parameters called “bound” variables and are local
(pass by value)
other variables used locally are called “free” variables and
are global
(load ‘file-name) ; enter lisp program from file
Conditionals
Predicates – return t for true or nil for false
atom, listp, null, numberp, typep
(member Elem List) – return tail of list beginning with first
occurrence of Element
(cond ( (predicate) (statement(s)) ) ) ; note use of cond
; Examples (note recursion at work):
(defun fac (n) ; recursive factorial (n!)
(cond ( (not (integerp n)) nil)
( (< n 0) nil)
( (equal n 0) 1 )
( t (* n (fac (1- n))))))
(defun mylength (l)
(cond ( (not (listp l) nil)
( (null l) 0 )
( t (1+ (mylength (cdr l))))))
(defun mylengthwithif (l)
(if (null l) 0 (1+ (mylength (cdr l)))))
(defun mymember (e l))
(cond ((atom l) nil)
((null l) nil)
((equal e (car l)) t )
( t (mymember e (cdr l)))))
(defun mypower (b n)
(cond ((or (not (numberp b)) (not (numberp n))) nil)
((< n 0) (/ 1.0 (mypower b (* -1 n))))
( t (* b (mypower b (1- n))))))
Using clisp
SOURCE CODE IN FILE kraft
(defun arithmetic (x)
(+ x (* x x) ) )
(defun main ()
(setq of (open “kraftout” :direction :output) )
(setq iof (open “kraftin” :direction :input) )
(terpri of)
(setq z (read iof) )
(setq y (arithmetic z) )
(print y of) )
DATA IN FILE kraftin
6
TERMINAL
clisp
(load ‘kraft)
(main)
(exit)
DATA IN FILE kraftout AFTER PROGRAM EXECUTION
42
Another example: powerset in Lisp
powerset is the set of subsets of a given set
SOURCE CODE IN FILE powerset
(defun long (l)
(cond ((null l) 0)
( t (1+ (long (cdr l))))))
(defun add (e l)
(cond ((or (atom l) (null l)) nil))
( t (cons (cons e (car l)) (add e (cdr l))))))
(defun power (l)
(cond ( (not (listp l)) nil)
( ( null l) (list l))
((equal (long l) 1) (list l (cdr l)))
( t (append (add (car l) (power (cdr l))) (power (cdr l))))) )
TERMINAL
clisp
(load ‘powerset)
(setq z ‘(a b c)
(power z))
(exit)
((A B C) (A B) (A C) (A) (B C) (B) (C) () )
Iteration
defun sum-of-ints (n) ; example of for command
(do ((i n (1- i))
(result 0 (+ i result)))
((zerop i) result)))
(prog1 (car stack) (setq stack (cdr stack)) ; note use of prog1
; prog1 evaluates expressions but returns result of first one
Property Lists ; databases (of sorts)
(setf (get ‘chair3 ‘color) ‘blue)
(get ‘chair3 ‘color) blue
Advanced Lisp
(defun sum-loop (func n) ; apply to use function as argument
(do ((i n (1- i))
(result 0 (+(apply func (list i)) result)))
((zerop i) result)))
(sum-loop ‘sqrt 5)
(defun squared (n) (* n n)) (sum-loop ‘squared 5)
(sum-loop (lambda (x) (* x x)) 5)
; lambda for unnamed functions
(setq x ‘(cons ‘a ‘(b c))) (eval x) (a b c) ; eval to evaluate a
symbol
(mapcar ‘1+ (100 200 300)) (101 201 301)
(mapcar ‘+ ‘(1 2 3) ‘(100 200 300)) (101 202 303)
; mapcar to use an operator on a list
I/O
(setq x (read)) (a b c) x (a b c)
(prog1 (print ‘enter) (setq x (read)) same result as above
; can use car and cdr to get individual elements of x
(loop ; use of loop and let to to read a number n and print n
(print ‘number >)
(let ((in (read)))
(if (equal in ‘end) (return nil))
(print (sqrt (in))))
Strings “characters”
List Representation (cons list)
Double linked list – left pointer points to value, right pointer points to
remainder
of list
dotted pair (a) = (a . nil) (a b c) = (a . (b . (c . nil)))
Equality (setq x ‘(a b c)) (setq y (cdr x)) (setq z ‘(b c))
(equal y z) t (eq y z) nil
; eq means same object not just same value
; eql works like eq except if symbols are numbers of same
type
and value
Functional Programming (FP) – Backus (Everything is a
function, returning a value; no assignment)
FP = (O,F,F,D), where:
O = set of objects, either atoms (e.g., numbers or symbols), sequences
(lists, denoted by <…>), or the bottom symbol which means
“undefined”;
F = set of functions, where, for each f F, f: O --> O;
Example: +: <1,2> 3
F = set of functional forms to make new functions
D = set of definitions to define functions in F and to assign names to
them
(Primitive) Functions
Selector s:x x=<x1,…,xn> & 1sn & s integer xs ;
Tail tl:x x=<x1> ; x=<x1,…,xn> & 2n <x2,…,xn>;
Identity id: x x
Atom atom: x (x is an atom) T; x F;
Equals eq:x x=<y,z> & y=z T; x=<y,z> & yz F;
Null null:x x= T; x F; ( = <> = empty sequence)
Reverse reverse:x x= ; x=<x1,…,xn> <xn,…,x1>;
Distribute from left (right)
distl:x x=<y,> ; x=<y,<z1,…,zn>>
<<y,z1>,…,<y,zn>>;
distr:x x=<,y> ; x=<<y1,…,yn>,z>
<<y1,z>,…,<yn,z>>;
Length length:x x=<x1,…,xn> n; x=> 0;
Transpose trans:x x=<,…,> ; x=<x1,…,xn> &
xi=<xi1,…,xim> i 1in
& yj=<x1j,…,xnj> j 1jm <y1,…,ym>;
Arithmetic
+:x x=<y,z> & y,z numbers y+z;
-:x x=<y,z> & y,z numbers y+z;
*:x x=<y,z> & y,z numbers y*z;
:x x=<y,z> & y,z numbers & z0 yz;
Boolean
and:x x=<T,T> T; x=<T,F> <F,T> <F,F> F;
or:x x=<F,F> F; x=<T,F> <F,T> <T,T> T;
not:x x=T F; x=F T;
Append left (right)
apndl:x x=<y, > <y>; x=<y,<z1,…,zn>
<y,z1,…,zn>;
apndr:x x=<,z > <z>; x=<<y1,…,yn>,z>
<y1,…,yn,z>;
Right Selectors; right tail
sr: x=<x1,…,xn> & 1sn & s integer xn-s+1;
tlr:x x=<x1> ; x=<x1,…,xn> & 2n <x1…,xn-1>;
Rotate left (right)
rotl:x x= ; x=<x1> <x1>; x=<x1,…,xn> &
2n <x2,…xn,x1>;
rotr:x x= ; x=<x1> <x1>; x=<x1,…,xn> & 2n
<xn,x1,…xn>;
Functional Forms
Composition (f 0 g):x f(g:x))
Construction [f1,…,fn]:x <f1:x,…,fn:x>
Condition (p --> f; g):x (p:x)=T f:x; (p:x)=F (g:x);
Constant ┐x:y y= ; x
Insert /f:x x=<x1> x1; x=<x1,…,xn> & 2n
f:<x1,f:<x2,…,xn>>;
Example: /+:<4,5,6> = +:<4, /+:<5,6>> = +:<4,+:<5,/+:<6>>>
= +:<4,+:<5,6>=+:<4,11>=15
Apply to all f:x x= ; x=<x1,…,xn> <f:x1,…,f:xn>>;
Binary to Unary (bu f x):y f:<x,y>
While (while p f):x (p:x)=T (while p f): (f:x); (p:x)=F x;
Definitions def l r where l is a symbol (function name) and r is an
expression
Example: def last (null 0 tl --> 1;last 0 tl)
Sample Programs
Factorial
def eq0 eq 0 [id, ┐0]
def sub1 - 0 [id, ┐1]
def ! (eq0 ┐1; * 0 [id, ! 0 sub1])
Inner Product def IP (/+) 0 (*) 0 trans
Matrix Multiplication def MM (IP) 0 (distl) 0 distr 0
[1,trans 0 2]
Bonus Homework Problems
1. Evaluate the following
a) 3 0 tl: <a,b,c,d>
b) tl 0 2: <a,b,c>
c) length 0 distl 0 reverse: <<1,2,3,4,5>,a>
d) (/+) 0 ( length): <<1>,<2,3>,<4,5,6>>
2. Write a non-recursive FP program to compute the mean of a
sequence of numbers (remember that the mean is the sum of the sequence
divided by the number of numbers in the sequence).
x (read)) same result as above
; can use car and cdr to get individual elements of x
(loop ; use of loop and let to to read a number n and print n
(print ‘number >)
(let ((in (read)))
(if (equal in ‘end) (return nil))
(print (sqrt (in))))
Prolog Logic Programming
Facts relation-name(arguments).
lower-case first letter constant
upper-case first letter variable
parent(pam,bob). parent(tom,bob). parent(tom,liz).
parent(bob,ann).
parent(bob,pat). parent(pam,jim).
pam tom
| / \
bob liz
/ \
ann pat
\
jim
Queries ? relation-name(arguments).
? parent(bob,pat). yes
? parent(liz,pat). no
? parent(X,liz). X=tom
? parent(bob,X). X=ann ; X=pat
? parent(X,Y).
, AND ; OR
Rules relation-name(arguments) :- relation-
name(arguments),
[…,relation-name(arguments)].
offspring(X,Y) :- parent(Y,X).
grandparent(X,Z) :- parent(X,Y),Parent(Y,Z).
Recursive rules
predecessor(X,Z) :- parent(X,Z).
predecessor(X,Z) :-
parent(X,Y),predecessor(Y,Z).
Problem – does order make a difference? Bonus – run this and
tell what happens
pred1(X,Z) :- parent(X,Z). pred1(X,Z) :-
parent(X,Y),pred1(Y,Z).
pred2(X,Z) :- parent(X,Y),pred2(Y,Z). pred2(X,Z) :-
parent(X,Z).
pred3(X,Z) :- parent(X,Z). pred3(X,Z) :-
pred3(X,Y),parent(Y,Z).
pred4(X,Z) :- pred4(X,Y),parent(Y,Z). pred4(X,Z) :-
parent(X,Z).
Declarative meaning versus
Procedural Goals Matching (Scanning)
Instantiation of variables
Structures date(Day,Month,Year) line(point(1,7),point(2,5)).
Horn clauses in logic Backtracking
Problem – suppose we add gender (e.g., male(jim). and
female(ann). facts to our knowledge base, then add the rule
sister(X,Y) :- parent(Z,X),parent(Z,Y),female(X). What weird
thing can happen? ann is ann’s sister! Welcome to Prolog world.
SOURCE CODE IN FILE kraft
main(X,Y) :- add(X,Y,Z),write(X),write(‘ ‘),write(Y),
write(‘ ‘),write(Z),nl.
add(A,B,C) := C is A + B.
TERMINAL
prolog
consult(kraft).
tell(kraftout).
main(3,4).
told.
halt.
DATA IN FILE kraftout AFTER PROGRAM EXECUTION
3 4 7
List Stuff
List
[a,b,c,d]
[a|b,c,d] a is head of list (car), [b,c,d] is tail of list (cdr)
[a, b| c, [d, e], f] allowed
Functions
member(X,[X|_]).
member(X,[_|Y]) :- member(X,Y).
concatenate([[,L,L).
concatenate([X|L1],L2,[X|L3]) :- concatenate(L1,L2,L3).
delete(X,[X|L],L).
delete([X,[H|L1],[H|L2]) :- delete(X,L1,L2).
add(X,L,L1) -: delete(X,L1,L).
sublist(S,L) :- concatenate(L1,L2,L),concatenate(S,L3,L2).
permute([],[]).
permute([X|L],P) :- permute(L,L1),add(X,L1,P).
Arithmetic
is assignment operator + - * / ** // mod
length([],0). length([_|Tail],L) :- length(Tail,N), L is N +1.
gcd(X,X,X). gcd(X,Y,D) :- X < Y, Y1 is Y - X,
gcd(X,Y1,D).
gcd(X,Y,D) :- Y < X, gcd(Y,X,D).
mypower(B,0,1.0).
mypower(B,N,P) :- N < 0,M is -N,mypower(B,M,Q),P is
1.0/Q.
mypower(B,N,P) :- M is N-1, mypower(B,M,Q), P is B * Q.
Monkey and Banana Problem
state(monkey-horizontal-position,monkey-verticalposition,box-
position,possession)
actions –walk, push, climb, grasp
_ unnamed variable nl newline write nl and write
always true
move(state(middle,onbox,middle,hasnot),grasp,state(middle,onbox
,middle,has)).
move(state(P,onfloor,P,H),climb,state(P,onbox,P,H)).
move(state(P1,onfloor,P1,H),push(P1,P2),state(P2,onfloor,P2,H)).
move(state(P1,onfloor,B,H),walk(P1,P2),state(P2,onfloor,B,H)).
canget(state(_,_,_,has),[]).
canget(State,[Action|Actions]) :-
move(State,Action,Newstate),canget(Newstate,Actions).
printactions([]).
printactions([X|Y]) :- write(X),nl,printactions(Y).
main(S,A) :- canget(S,A),printactions(A).
Word Problem
There are five houses on a block in a city, with a different man of a
different nationality and who smokes a different brand of cigarettes
(politically incorrect) living in each house. Each man has a
different pet and drinks a different drink. Moreover, each house is
a different color. Now,7 just the facts: 1) the Englishman lives in
the red house, 2) the Spaniard has a dog, 3) the man living in the
green house prefers coffee, 4) the Ukranian drinks tea, 5) the man
with the snail smokes Winstons, 6) the man in the yellow house
smokes Kools, 7) the man who prefers orange juice also prefers
Lucky Strikes to smoke, 8) the Japanese man prefers to smoke
Parliaments, 9) the man in the middle house prefers milk, 10) the
man in the first house is a Norwegian, 11) one house has a zebra,
12) one house has a man who prefers water, 13) the man who has a
fox lives next to the man who smokes Chesterfields, 14) the man
who has a horse lives next to the man who smokes Kools, 15) the
Norwegian lives next to a blue house, and 16) the green house is to
the immediate right of the ivory house. Now, who lives where,
who has which pet and which drink and which cigarette brand, and
what color are the houses?
Answer:
the first house is yellow with the Norwegian, a fox, with
water and Kools; the second house is blue with the Ukranian, a
horse, with tea and Chesterfields; the third house is red with the
Englishman, a snail, with milk and Winstons; the fourth house is
ivory with the Spaniard, a dog, with orange juice and Lucky
Strikes; the fifth house is green with the Japanese, a zebra, with
coffee and Parliaments
puzzle :-
Houses = [_,_,house(_,_,_,milk,_),_,_],
Houses = [house(_,norwegian,_,_,_),_,_,_,_],
memberp(house(red,english,_,_,_),Houses),
memberp(house(_,spanish,dog,_,_),Houses),
memberp(house(green,_,_,coffee,_),Houses),
memberp(house(_,ukranian,_,tea,_),Houses),
memberp(house(_,_,snail,_,winston),Houses),
memberp(house(yellow,_,_,_,kools),Houses),
memberp(house(_,_,_,orangejuice,luckystrikes),Houses),
memberp(house(_,japanese,_,_,parliaments),Houses),
memberp(house(_,_,zebra,_,_),Houses),
memberp(house(_,_,_,water,_),Houses),
nexto(house(_,_,_,_,chesterfields),house(_,_,fox,_,_),Houses),
nexto(house(_,_,_,_,kools),house(_,_,horse,_,_),Houses),
nexto(house(_,norweigian,_,_,_),house(blue,_,_,_,_),Houses),
rightof(house(green,_,_,_,_),house(ivory,_,_,_,_),Houses),
printhouses(Houses).
memberp(X,[X|_]).
memberp(X,[_|Y]) :- memberp(X,Y).
nexto(X,Y,[X,Y|_]).
nexto(X,Y,[Y,X|_]).
nexto(X,Y,[_|Z]) :- nexto(X,Y,Z).
rightof(X,Y,[Y,X|_]).
rightof(X,Y,[_|Z]) :- rightof(X,Y,Z).
printhouses([]).
printhouses([X|Y]) :- write(X),nl,printhouses(Y).
8 Queens
Eight queens – put eight queens on a 8x8 chessboard where no
queen can attack another queen – remembering that queens can
move up or down, left or right, and diagonally as much as they
like.
answer(L) :- template(L),solution(L),write(L),nl.
template([1/Y1,2/Y2,3/Y3,4/Y4,5/Y5,6/Y6,7/Y7,8/Y8]).
solution([]).
solution([X/Y|Others]) :- solution(Others),member(Y,
[1,2,3,4,5,6,7,8]),
noattack(X/Y,Others).
noattack(_,[]).
noattack(X/Y,[X1/Y1|Others]) :- Y =\= Y1,Y1-Y =\= X1-X, Y1-Y
=\= X-X1,
noattack(X/Y,Others).
member(X,[X|_]).
member(X,[Y|L]) :- member(X,L).
Controlling backtracking (the cut !)
f(X,0) :- X<3. f(X,2) :- 3=<X, X<6. f(X,4):-6=<X. ?
f(1,Y),2<Y. no
cut instantiations before cut stay as is and cannot be changed
f(X,0) :- X<3,!. f(X,2) :- X<6,!. f(X,4).
max(X,Y,X) :-X>=Y,!. max(X,Y,Y).
Suppose we have a programming contest and players are winners if
they win every match, fighters if they win some and lose some, and
sportsman if the lose all contests. Beat(X,Y) implies player X
played and beat (won) player Y.
Class(X,fighter) :- beat(X,_),beat(_,X),!. class(X,winner) :-
beat(X,_),!.
Class(X,sportsman) :- beat(_,X).
Suppose mary likes all animals but snakes.
likes(mary,X) :- snake(X),!,fail. likes(mary,X) :-
animal(X).
or likes(mary,X) :- animal(X), not snake(X).
Or,
different(X,X) :- !,fail. different(X,Y).
; can use to make sure ann is not her own sister as before
different(X,Y) :- X = Y,!,fail ; true.
Java Tutorial
File: Welcome1.java
// A first program in Java comment
public class Welcome1 { // class definition for Welcome1
{
public static void main( String args[] )
// needed - main
{
System.out.println( "Welcome to Java Programming!" );
// System.out = main output object,
// println = method for that object
} // end of main
} // end of Welcome1 class
Compiler: javac Welcome1.java Welcome1.class =
fle with bytecode
Execution: java Welcome1
File: Welcome4.java
// A welcome program in Java in a dialog box
import javax.swing.JOptionPane; // import JOptionPane class
public class Welcome4
{
public static void main( String args[] )
{
JoptionPane.showMessageDialog(
null,"Welcome\nto\nJava\nProgramming!" );
// ShowMessageDialog = method for
JOptionPane class
….null first argument
System.exit ( 0 ); // terminate the program
}
}
File: Addition.java
// An addition program
import javax.swing.JOptionPane;
public class Addition {
public static void main( String args[] )
String firstNumber,
secondNumber; // numbers entered by user
int number1,
number2,
sum; // local variables - integers
firstNumber = JOptionPane.showInputDialog( "Enter
first integer" );
secondNumber =
JOptionPane.showInputDialog( "Enter second
integer" );
// read in the two numbers as strings
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// convert numbers from strings to integers
{ sum = number1 + number2;
// add the numbers
JoptionPane.showMessageDialog(
null,"The sum is " + sum, "Results",
JOptionPane,PLAIN_MESSAGE );
// display results, null is first parameter, "Results"
is the title of the
// display box, PLAIN_MESSAGE is fourth
parameter
System.exit ( 0 );
}
}
File: WelcomeApplet.java
// WecomeApplet.java - A first welcome applet in Java
import javax.swing.JApplet; // import JApplet class
import java.awt.Graphics; // import Graphics class
public class WelcomeApplet extends JApplet { // extension of
class - inheritance
{
public void paint( Graphics g ) // defintion of object g's
paint method
{
g.drawstring( "Welcome to Java Programming!", 25,
25 );
// drawstring method and numbers are
coordinates
}
}
Compiler: javac WelcomeApplet.java WelcomeApplet.class
File: WelcomeApplet.html
<html><applet code="WelcomeApplet.class" width=300
height=30></applet></html>
Execution: appletviewer WelcomeApplet.html
File: AdditionApplet.java
// AdditionApplet.java – An ddition program with two floating
// point numbers
import java.awt.Graphics; // import Graphics class
import javax.swing; // import JApplet package
public class AdditionApplet extends Japplet {
double sum;
public void init()
{
String firstNumber,
secondNumber;
double number1,
number2;
firstNumber = JOptionPane.showInputDialog( "Enter
first real number" );
secondNumber = JOptionPane.showInputDialog
( "Enter second real number" );
// read in the two numbers as strings
number1 = Double.parseDouble( firstNumber );
number2 = Double.parseDouble( secondNumber );
// convert numbers from strings to
double reals
{ sum = number1 + number2;
}
public void paint( Graphics g ) // draw results
{
g.drawRect( 15, 10, 270, 20 ); // coordinates
g.drawstring( "The sum is " + sum, 25, 25 );
}
}
Compiler: javac AdditionApplet.java AdditionApplet.class
File: Addition.Applet.html
<html><applet code="AdditionApplet.class" width=300
height=50></applet></html>
Execution: appletviewer AdditionApplet.html
AWK (Aho, Weinberger, Kernighan) Interpretive
No declarations – type determined in context
awk –f programfilename datafilename [ >
outputfilename ] nawk
BEGIIN{ … } { /* pattern section … } End{ … }
order important but not all sections needed
C based ; only needed if more than one statement on
a line
Example: BEGIN{ print “Hello World!; exit}
Example: BEGIN{ i = 75; j = 30;
while(i >= j) {
If (i > j) i -= j
Else j -= i
}
print “The greatest common divisor” \
“of 75 and 30 is “ i
exit
}
Example { arg1 = $1; arg2 = $2
while(arg1 >= arg2) {
If (arg1 > arg2) arg1 -= arg2
Else arg2 -= arg1
}
print “The greatest common divisor of” $1 \
“and “ $2 is “ arg1
}
Example BEGIN{ sum_of_squares = 0 }
# This line is optional - default – numerical variables
# initialize automatically to 0, character variables to the
# null string
{ sum_of_squares += $1*$1 }
# Default internal loop to read input data and process it
# – one line at a time
END{ root_mean_square = sqrt(sum_of_squares)
/ NR
print root_mean_square
}
Internal variables
$i = the ith field of current record
$0 = entire current record
NR = number of records read to this point
$NF = number of fields in the current record
FS = input field separator
RS = input record separator
OFS = output field separator
ORS = output record separator
Example BEGIN{ FS = “;” }
{ print NR, $0 } # prints file with line numbers
# , standard spacing, lack of comma means
concatenation
Patterns assume a match before each statement in pattern
(middle) section
Assumed true if no pattern present
Default action if no statement present is to print
current line
Boolean - ==, !=, >, >=, <, <=
Match - ~, !~ match means presence of
pattern
in target
Example { NF >= 2
for (i=1; i<=NF; i++) sum[i]+= $i
cnt++
}
END{ for (i=1; i<=NF; i++)
printf “%g “, sum[i]
printf “\n”
print cnt “ records with 2 or more
fields”
}
| alternation a|b means ‘a’ or ‘b’
+ one or more a+ means one or more ‘a’
? means zero or one a? means one or zero ‘a’
occurrences
* means zero or more a* means zero or more ‘a’
occurrences
^ means beginning anchor so ^a means field begins
with ‘a’
$ means ending anchor so a$ means field ends with ‘a’
. means any
character
[…] means class [a-z] means any lower-case letter
[ab] means ‘a’ or ‘b’
Exanples
$2 ~ /a/ means match true if ‘a’ in field $2
$3 !~ /b/ means match true if no ‘b’ in field $3
$4 ~ /^this$|^that$/ means match true if field $4
=
‘this’ or field $4 = ‘that’
/start/,/stop/ means to start action if ‘start’
ccurs and keep doing it until ‘stop’ occurs
Logical connectives || OR $$ AND
Quiz: what do these programs do?
{ length > 69 }
{ /don/ }
{ !/!/ }
{ /hello/,/goodbye/ }
{ $1 != prev { print; prev = $1 }
More exit, length(.), sqrt(.), log(.), exp(.), int(.),
next, substr(.,.,.), index(..), split(.,.), printf
format, whle, for, concatenation operations,
files, arrays
Applications
In Unix, date must be reformatted
Counting words