Title: Programming Languages
1Programming Languages
- Syllogisms and Proof by Contradiction
- Midterm Review
2Notions of Truth
Propositions Statements that can be either True
or False
Truth Are there well formed propositional
formulas (i.e., Statements) that return True when
their input is True truth1 (Bool -gt Bool) -gt
Bool truth1 wff (wff True) truth2 (Bool -gt
Bool -gt Bool) -gt Bool truth2 wff (wff True
True) ( \ p -gt not p) ( \ p q -gt (p q)
(not p gt q)) ( \ p q -gt not p gt q) ( \ p q -gt
(not p q) (not p gt q) )
If it was never possible for it not to be True
that something was going to exist, and it will
never be possible for it not to be True that
something existed in the past then it is
impossible for Truth ever to have had a beginning
or ever to have an end. That is, it was never
possible that Truth cannot be conceived not to
exist. If R is something that can be conceived
not to exist and T is something that cannot be
conceived not to exist and T is greater than R
and God is that, than which nothing greater can
be conceived, then God exists and is Truth.
3Proof by Contradiction
Facts
- A is an Animal.
- A Barks.
- A is a Dog - A is an Animal, A Barks. (A is a
Dog IF A is and Animal AND A Barks) -
-
, - -(A is a Dog)
-
Database
Rule
Query (If you want to know if A is a Dog based
upon the Facts and Rules in the Database try to
see if A is not a Dog.)
? Contradiction Therefore A is a Dog
Can this reasoning be automated?
4Syllogisms
Note this is Prolog notation. In standard
notation, this would be P ? Q.
P implies Q (i.e., Q is True if P is True or If P
is True then Q is True)
Syllogism e.g., Modus Ponens 1). P is True
2). P ? Q is True, therefore Q is True.
Green assume 2 things the implied Result is in
Red if the result is just True, then the
syllogism is Valid, if the results are True and
False, then the syllogism is Invalid.
5Proof by Contradiction
P1 P2
1). Let P Its raining, Im outside (comma
means ) 2). P1. (P1 is True, i.e., its
raining) 3). P2. (P2 is True, i.e., Im
outside) 4). Q - P Im wet - Its raining,
Im outside. (if its raining and Im
outside then Im wet) 5). Q (To answer the
Query Am I wet against the Database, assume Im
not wet) 6). (Its raining, Im outside)
( From 4 and 5 and Pattern 1 ) 7). Im
outside
( From 2 and 6 and Pattern 2 ) 8). Contradiction
Therefore Im wet ( From 3 and 7 and
Pattern 3 )
Facts
Rule
Pattern 1 (Modus Tollens) Q - (P1, P2). -Q ?
-(P1, P2) Pattern 2 (Affirming a
Conjunct) P1. -(P1, P2) ? -P2 Pattern
3 P2. -P2 ? Contradiction
Database
P
R
S
6Proof by Contradiction
- A is an Animal.
- A Barks.
- A is a Dog - A is an Animal, A Barks.
- -(A is a Dog)
- 3 and 4 and Pattern 1 ? -(A is an Animal, A
Barks) - 1 and 5 and Pattern 2 ? -A Barks
- 2 and 6 and Pattern 3 ? Contradiction
- Therefore A is a Dog
Database
Query (If you want to know if A is a Dog based
upon the Facts and Rules in the Database try to
see if A is not a Dog.)
7Midterm Review
- What we cannot speak about we must pass over in
silence. - The world consists of independent atomic
factsexisting states of affairsout of which
larger facts are built. - Language consists of atomic, and then
larger-scale, propositions that correspond to
these facts by sharing the same "logical form". - Thought, expressed in language, "pictures" these
facts. - Tractatus
8Previous Midterm Exam
9Study All the Homework and Quizzes
10Functional Programming (Relation Programming)
Universe (Concepts for building a lisp
interpreter)
T. Skolem World
Relation Function Primitive Recursive Functions Primitive Recursive Arithmetic Primitive Recursive Relations Gödel's Incompleteness Theorem
A. Church and H. Curry World
? calculus Alpha-conversion Beta Reduction Combinator Logic ltSgt, ltKgt, ltBgt, ltCgt, ltYgt, and cond
J. McCarthy and G. Sussman/G. Steel World
Lisp / Scheme First-Class Functions Function Definition (lambda) e.g., (lambda (x) x) Function Application (f a) Substitution (let) e.g., (let ((x 3)) x) car, cdr, cons, s-expressions foldr, foldl, map Dynamic / Static Scoping
S. Krishnamurthi World
PLAI AE, WAE, FAE Function Definition (fun) e.g., (fun (x) x) Function Application (app) e.g., (app (id 'f) (id 'a)) Substitution (with) e.g., (with (x 3) x) Converting withs to (f a) (I.e., the FAE parser converts concrete syntax to abstract syntax) Environment / Closures Dynamic / Static Scoping Lazy / Eager Evaluation (interp (parse expr) Env.)
11High Level Language Universe (Concepts for
building a HLL interpreter like ReL)
N. Chomsky Regular Grammar World
Regular Grammar Regular Expressions Finite State Machines Token (Non-Terminal) Lexical Analyzer (Tokenizer) Parser.jj ./grammar/Python.g
N. Chomsky Regular Context Free Grammar World
Context-free Grammar BNF EBNF Terminal Syntactic Analyzer (Parser) Internal Parse Tree Ambiguous Grammar Parser.jj ./grammar/Python.g
Abstract Syntax Tree World
Nodes on an AST ./src/org/python/antlr/ast ./dist/bin/jython ast/astview.py file.py
Interpreter World
Process an AST Visitor Pattern Symbol Table Type Checking Runtime Stack / Activation Record SQL, SIM RDF/RDFS/OWL/SPARQL ./src/org/python/antlr/ast/Tuple.java ./org/python/core/PyTuple.java
Tools
javacc / JJTree / JTB / JJDoc o Antlr ant SQLDeveloper jDeveloper or Eclipse jSQLParser
12(No Transcript)
13Relations and Functions
Relations A Relation is a subset of the
cross-product of a set of domains. Functions An
n-ary relation R is a function if the first n-1
elements of R are the functions arguments and
the last element is the functions results and
whenever R is given the same set of arguments, it
always returns the same results. Notice, this is
an unnamed function!.
14Function Bodies
With the same goals as Alfred Whitehead and
Bertrand Russell in Principia Mathematica (i.e.,
to rid mathematics of the paradoxes of the
infinite and to show that mathematics is
consistent) but also to avoid the complexities of
mathematical logic - The foundations of
elementary arithmetic established by means of the
recursive mode of thought, without use of
apparent variables ranging over infinite domains
Thoralf Skolem, 1923
Thoralf Skolem
In a small town there is only one barber. This
man is defined to be the one who shaves all the
men who do not shave themselves. The question is
then asked, 'Who shaves the barber?' If the
barber doesn't shave himself, then -- by
definition -- he does. And, if the barber does
shave himself, then -- by definition -- he does
not. or Consider the statement 'This statement is
false. If the statement is false, then it is
true and if the statement is true, then it is
false.
This article can be found in From Frege to
Gödel A Source Book in Mathematical Logic,
1879-1931 (Source Books in the History of the
Sciences)
A function is called primitive recursive if there
is a finite sequence of functions ending with f
such that each function is a successor, constant
or identity function or is defined from preceding
functions in the sequence by substitution or
recursion.
15Primitive Recursive Functions and Arithmetic (see
A Profile of Mathematical Logic by Howard
Delong pages 152 160)
- Thoralf Skolem The foundations of elementary
arithmetic by means of the recursive mode of
thought, without the use of apparent variables
ranging over infinite domains (1919, 1923). - He assumed that the following notions are already
understood - natural number (0 is included in the book),
- successor of x (i.e., x),
- substitution of equals (if x y and y z, then
x z), - and the recursive mode of thought (see next
page).
16Primitive Recursive Functions and Arithmetic (see
A Profile of Mathematical Logic by Howard
Delong pages 152 160)
- The addition function
- Book notation Relation notation
Arithmetic notation - f(x, 0) x (x 0 x)
x 0 x - f(x, y) (f(x, y)) (x y ( x y
b)) x y (x y) - Example 2 3 (The similar example of 7 5 on
pages 153-154 is actually a bit flawed as a
comparison with the following will show) - (0
0 0) 2 0 2 - (0 0
(0 0 b)) - gt (0 0 (0))
gt (0 0 0) 2 1 3 - (0 0
(0 0 b)) - gt (0 0 (0))
gt (0 0 0) 2 2 4 - (0 0
(0 0 b)) - gt (0 0 (0))
gt (0 0 0) 2 3 5
17Primitive Recursive Functions and Arithmetic (see
A Profile of Mathematical Logic by Howard
Delong pages 152 160)
- We may summarize the situation by saying that
while the usual definition of a function defines
it explicitly by giving an abbreviation of that
expression, the recursive definition defines the
function explicitly only for the first natural
number, and then provides a rule whereby it can
be defined for the second natural number, and
then the third, and so on. The philosophical
importance of a recursive function derives from
its relation to what we mean by an effective
finite procedure, and hence to what we mean by
algorithm or decision procedure. DeLong, page
156
18Primitive Recursive Functions and Arithmetic (see
A Profile of Mathematical Logic by Howard
Delong pages 152 160)
- A Sequence of Functions from definitions on
DeLong, page 157
Book notation Relation notation Relation notation Arithmetic notation
f1(x) x (x ( x 1)) (x ( x 1)) f1 is the successor function
f2(x) x (x x) (x x) f2 is the identity function with i 1
f3(y, z, x) z (y z x z) (y z x z) f3 is the identity function with i 2
f4(y, z, x) f1(f3(y,z,x)) (y z x ((x ( x 1)) (y z x z))) (y z x ((x ( x 1)) (y z x z))) f4 is defined by substitution for f1 and f3
This is how you would do this in lisp This is how you would do this in lisp This is how you would do this in lisp This is how you would do this in lisp
(let ((f1 (lambda (x) ( x 1))) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (f4 2 4 6))) (let ((f1 (lambda (x) ( x 1))) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (f4 2 4 6))) (let ((f1 (lambda (x) ( x 1))) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (f4 2 4 6))) (let ((f1 (lambda (x) ( x 1))) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (f4 2 4 6)))
f5(0, x) f2(x) (0 x ( x x)) f5(y, x) f4(y, f5(y,x), x) (not doable yet) f5(0, x) f2(x) (0 x ( x x)) f5(y, x) f4(y, f5(y,x), x) (not doable yet) f5 is defined by recursion and f2 and f4 f5 is defined by recursion and f2 and f4
f5 is primitive recursive addition f5 is primitive recursive addition f5 is primitive recursive addition f5 is primitive recursive addition
(let ((f1 (lambda (x) ( x 1))) (f2 (lambda (x) x)) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (letrec ((f5 (lambda (a b) (if ( a 0) (f2 b) (f4 (- a 1) (f5 (- a 1) b) b))))) (f5 2 3)))) (let ((f1 (lambda (x) ( x 1))) (f2 (lambda (x) x)) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (letrec ((f5 (lambda (a b) (if ( a 0) (f2 b) (f4 (- a 1) (f5 (- a 1) b) b))))) (f5 2 3)))) (let ((f1 (lambda (x) ( x 1))) (f2 (lambda (x) x)) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (letrec ((f5 (lambda (a b) (if ( a 0) (f2 b) (f4 (- a 1) (f5 (- a 1) b) b))))) (f5 2 3)))) (let ((f1 (lambda (x) ( x 1))) (f2 (lambda (x) x)) (f3 (lambda (y z x) z))) (let ((f4 (lambda (y z x) (f1 (f3 y z x))))) (letrec ((f5 (lambda (a b) (if ( a 0) (f2 b) (f4 (- a 1) (f5 (- a 1) b) b))))) (f5 2 3))))
19Primitive Recursive Functions and Arithmetic (see
A Profile of Mathematical Logic by Howard
Delong pages 152 160)
- Primitive Recursive Relations on DeLong, pages
158-159 - Example of eq primitive recursive relation
- (letrec ((pd (lambda (x) (if ( x 0) 0 (- x 1))))
- (dm (lambda (x y) (if ( y 0) x (pd
(dm x (pd y)))))) - (abs (lambda (x y) ( (dm x y)(dm y
x)))) - (sg (lambda (x) (if ( x 0) 0 1)))
- (eq (lambda (x y) (sg (abs x y)))))
(eq 1 1))
20A little Bit of Lambda Calculus Lambda
Expressions
- The manipulation of meaningless symbols?
- ________________________________________________
- A lambda expression is a particular way to define
a function - LambdaExpression ? variable (M N) ( ?
variable . M ) - M ? LambdaExpression
- N ? LambdaExpression
- E.g., ( ? x . (sq x) ) represents applying the
square function to x.
21A little Bit of Lambda Calculus Properties of
Lambda Expressions
- In (? x . M), x is bound. Other variables in M
are free. - A substitution of N for all occurrences of a
variable x in M is written Mx ? N. Examples - An alpha-conversion allows bound variable names
to be changed. For example, alpha-conversion of
?x.x might yield ?y.y. - A beta reduction ((? x . M)N) of the lambda
expression (? x . M) is a substitution of all
bound occurrences of x in M by N. E.g., - ((? x . x2) 5) 52
22Lambda Calculus
Lambda Calculus
?x.x
?s.(s s)
?func.?arg.(func arg)
def identity ?x.x def self_apply ?s.(s s) def apply ?func.?arg.(func arg)
def select_first ?first.?second.first def select_second ?first.?second.second
def cond ?e1.?e2.?c.((c e1) e2)
def trueselect_first def falseselect_second def not ?x.(((cond false) true) x) Or def not ?x.((x false) true)
def and ?x.?y.(((cond y) false) x) Or def and ?x.?y.((x y) false)
def or ?x.?y.(((cond true) y) x) Or def or ?x.?y.((x true) y)
23Lambda Calculus Substitution
In lambda calculus, if cond is defined as def
cond ?e1.?e2.?c.((c e1) e2), def and
?x.?y.(((cond y) false) x) is equivalent to def
and ?x.?y.((x y) false) because (((cond y)
false) x) (((?e1.?e2.?c.((c e1) e2) y) false)
x) ((?e2.?c.((c y) e2) false) x) (?c.((c y)
false) x) ((x y) false) In lambda calculus, if
cond is defined as def cond ?e1.?e2.?c.((c e1)
e2), def or ?x.?y.(((cond true) y) x) is
equivalent to def or ?x. ?y.((x true) y)
because (((cond true) y) x) (((?e1.?e2.?c.((c
e1) e2) true) y) x) ((?e2.?c.((c true) e2) y) x)
(?c.((c true) y) x) ((x true) y)
24Simple Lisp in Scheme
- (letrec ( (first (lambda (List) (if (null? List)
(list) (car List)))) - (sum-list (lambda (List) (if (null?
List) 0 ( (car List) (sum-list (cdr List)))))) - (nth (lambda (N List) (if (not ( N
0))(nth (- N 1) (cdr List))(car List)))) - (head (lambda (N List) (if ( N 0)
(list) (cons (car List) (head (- N 1) (cdr
List)))))) ) - (nth 1 (list 1 2 3)))
- ? 2
- (letrec ( (List (list 1 2 3 4 5 6))
- (first (lambda (List) (if (null?
List) (list) (car List)))) - (sum-list (lambda (List) (if (null?
List) 0 ( (car List) (sum-list (cdr List)))))) - (nth (lambda (N List) (if (not ( N
0))(nth (- N 1) (cdr List))(car List)))) - (head (lambda (N List) (if ( N 0)
(list) (cons (car List) (head (- N 1) (cdr
List)))))) ) - (head (nth 1 List) List) )
- ? (list 1 2)
- Code for Chaitin page 43 - 44
- (letrec ( (map (lambda (Function List) (if (null?
List) List (cons (Function (car List)) (map
Function (cdr List))) )) ) - (factorial (lambda (N) (if ( N 0)
1 ( N (factorial (- N 1)))))) )
25Develop Substitution for the Following
Expressions
Start with schema from Chapter 2 Get the
following expressions to work (subst (id 'x) 'x
(id 'y)) (subst (num 2) 'x (num 1)) (subst (id
'x) 'x (num 1)) (subst (id 'y) 'x (num
1)) (subst (add (id 'x) (id 'x)) 'x (num
1)) (subst (with 'y (num 2) (id 'x)) 'x (num
1)) (subst (with 'y (num 2) (add (id 'x) (id
'y))) 'x (num 1)) (subst (with 'y (id 'x) (add
(id 'x) (id 'y))) 'x (num 1)) (subst (with 'x
(id 'x) (id 'x)) 'x (num 1)) (calc (subst (with
'y (add (num 2) (id 'x)) (add (id 'y)(id 'x))) 'x
(num 1)))
26Scheme for Textbook Chapter 3
lang plai (define-type WAE num (n number?)
add (lhs WAE?) (rhs WAE?) sub (lhs WAE?)
(rhs WAE?) with (name symbol?) (named-expr
WAE?) (body WAE?) id (name symbol?))
subst WAE symbol WAE!WAE (define (subst expr
sub-id val) (type-case WAE expr
num (n) expr add (l r) (add
(subst l sub-id val)
(subst r sub-id val)) sub (l r)
(sub (subst l sub-id val)
(subst r sub-id val)) with
(bound-id named-expr bound-body)
(if (symbol? bound-id sub-id)
(with bound-id
(subst named-expr sub-id val)
bound-body) (with
bound-id (subst
named-expr sub-id val)
(subst bound-body sub-id val)))
id (v) (if (symbol? v sub-id) val expr)))
calc WAE!number (define (calc expr)
(type-case WAE expr num (n) n
add (l r) ( (calc l) (calc r))
sub (l r) (- (calc l) (calc r))
with (bound-id named-expr bound-body)
(calc (subst bound-body
bound-id
(num (calc named-expr))))
id (v) (error 'calc "free identifier")))
27 28let transformation, differed substitution and
closures, and interpretation in FAE let
transformation (let ((A B)) C) ((lambda (A)
C) B) A B ---------------- C
------------------- A
---------- B -------- C (let (( x 3)) (let ((f
(lambda (y) ( x y)))) (f 4)) ((lambda (x)
((lambda (f) (f 4)) (lambda (y) ( x y))))
3) (app (fun 'x app (fun 'f app (id 'f) (num
4)) (fun 'y (add (id 'x) (id 'y)))) (num 3))
(app ------- arg1
------------------ ------------arg2--------------
- (app ---------------------------------------
arg1-------------------------------------
--arg2 Differed substitution and closures (aSub
'f (closureV 'y (add (id 'x) (id 'y)) (aSub 'x
(numV 3) (mtSub))) (aSub 'x (numV 3)
(mtSub))) Interpretation (interp (app (id 'f)
(num 4)) (aSub 'f (closureV 'y (add (id 'x) (id
'y)) (aSub 'x (numV 3) (mtSub))) (aSub 'x (numV
3) (mtSub))))
(numV 7)
29Static and Dynamic Scoping Static
scoping (interp (parse 'with x 5 f 4)
(aSub 'f (closureV 'y (add (id 'x) (id 'y)) (aSub
'x (numV 3) (mtSub))) (aSub 'x (numV 3)
(mtSub)))) (numV 7) Dynamic Scoping (interp
(parse 'with x 5 f 4) (aSub 'f (closureV 'y
(add (id 'x) (id 'y)) (aSub 'x (numV 3) (mtSub)))
(aSub 'x (numV 3) (mtSub)))) (numV 9) Think
about this expression for both Static and Dynamic
Scoping (let ((z 3)) (let ((d 3) (f (lambda (x)
x))) (let ((z 27))
(let ((z 3) (a 5) (x (lambda (x y) ( x ( y
z))))) (let ((z 9) (a 7)) (x z a))))))
30Recursive Functions Exemplified by foldr in lisp
(letrec ((f (lambda (l) (if (null? l) '()
(cons (car l) (f (cdr l))))))) (f '(1 2 3 4 5
6))) '(1 2 3 4 5 6) (letrec ((f (lambda (v l)
(if (null? l) v (cons (car l) (f v (cdr
l))))))) (f '() '(1 2 3 4 5 6))) '(1 2 3 4 5
6) (letrec ((f (lambda (f1 v l) (if (null? l)
v (f1 (car l) (f f1 v (cdr l))))))) (f
cons '() '(1 2 3 4 5 6))) '(1 2 3 4 5 6) f
foldr If f1 cons, foldr is the identity
function for a list. Its the same as (cons 1
(cons 2 (cons 3( cons 4 (cons 5 (cons 6 '()))))))
(cons 1 (cons 2 (cons 3 (cons 4 (cons
5 (cons 5 '()))))))
(cons 1 (cons 2 (cons 3 (cons 4 (cons
5 (cons 5 '()))))))
This can be thought of as a stack with conss on
it.
Here the stack is upside down
31Recursive Functions Exemplified by foldl in lisp
(letrec ((f (lambda (f1 v l) (if (null? l)
v (f f1 (car l) (cdr l)))))) (f cons '() '(1
2 3 4 5 6))) 6 (letrec ((f (lambda (f1 v l) (if
(null? l) v (f f1 (f1 (car l) v) (cdr
l)))))) (f cons '() '(1 2 3 4 5 6))) '(6 5 4 3 2
1) f foldl If f1 cons, foldl reverses the
list. foldl is tail-recursive because nothing
goes on the stack. Its the same as (cons 6 (cons
5 (cons 4 ( cons 3 (cons 2 (cons 1 '()))))))
Nothing goes on the stack in this case.
32PLAI Chapters 4, 5 and 6
Chapter 6, Pages 41 42 first-order Functions
are not values in the language. They can only be
defined in a designated portion of the program,
where they must be given names for use in the
remainder of the program. The functions in F1WAE
are of this nature, which explains the 1 in the
name of the language. higher-order Functions can
return other functions as values. first-class
Functions are values with all the rights of other
values. In particular, they can be supplied as
the value of arguments to functions, returned by
functions as answers, and stored in data
structures.
Page 27 - "
33A Different Road to High-level Languages
34Well be starting with javacc ? moving to ANTLR
later
Instance of a Programming Language
int main () return 0
Internal Parse Tree
Program (abstract syntax) Function main
Return type int params Block
Return Variable returnmain, LOCAL
addr0 IntValue 0
Abstract Syntax
35Syntax and Grammar Parser.jj
PARSER_BEGIN(Parser) import java.io. import
java.util. public class Parser public
static void main(String args) throws
ParseException Parser parser new Parser
(System.in) parser.ae()
PARSER_END(Parser ) SKIP " "
"\t" "\n" "\r" lt"//" ("\n","\r")
("\n""\r")gt TOKEN lt LCURLY "" gt
lt RCURLY "" gt lt MINUS "-" gt lt
PLUS "" gt TOKEN / Literals /
lt INTEGER ("0"-"9") gt TOKEN
ltERROR gt
Parser
Grammar Production Rules
void ae() Token n n ltINTEGERgt
System.out.print("(num " n ")")
list() void list() LOOKAHEAD(2)
ltLCURLYgt ltPLUSgt System.out.print(" (add ") (
ae() ) ltRCURLYgt System.out.print(") ")
ltLCURLYgt ltMINUSgt
System.out.print(" (sub ") ( ae() ) ltRCURLYgt
System.out.print(") ")
Tokens, Terminals
36Example Javacc Parser
void program() ( rels() ) ( comps()
) void rels() String id
ltRELATIONgt ( id identifier()
System.out.println(" Saw IDENTIFIER " id)
) System.out.println("Saw a RELATION")
String identifier() Token t t
ltIDENTIFIERgt return new String(t.image)
void comps() String id1, id2
ltCOMPOSEgt id1 identifier() ltWITHgt id2
identifier() System.out.println("Saw
Composiiton of " id1 " with " id2)
PARSER_BEGIN(Rel) import java.io. import
java.util. public class Rel public
static void main(String args) throws
ParseException Rel parser new
Rel(System.in) parser.program()
PARSER_END(Rel) SKIP " " "\t"
"\n" "\r" lt"//" ("\n","\r")
("\n""\r")gt TOKEN lt RELATION
"Relation" gt lt COMPOSE "Compose" gt lt
WITH "with" gt TOKEN / Literals /
lt IDENTIFIER "A"-"Z", "a"-"z"
( "A"-"Z", "a"-"z", "0"-"9", "_" )
gt TOKEN ltERROR gt
37Chomsky Hierarchy
- Regular grammar used for tokenizing
- Context-free grammar (BNF) used for parsing
- Context-sensitive grammar not really used for
programming languages
38Regular Grammar
- Simplest least powerful
- Equivalent to
- Regular expression (think of perl)
- Finite-state automaton
- Right regular grammar
- ? Terminal,
- A and B ? Nonterminal
- A ? ? B
- A ? ?
- Example
- Integer ? 0 Integer 1 Integer ... 9 Integer
- 0 1 ... 9
39Regular Grammar
- Less powerful than context-free grammars
- The following is not a regular language
- an bn n 1
- i.e., cannot balance ( ), , begin end
40Regular Expressions
x a character x \x an escaped character,
e.g., \n name a reference to a name M
N M or N M N M followed by N M zero or
more occurrences of M M One or more
occurrences of M M? Zero or one occurrence of
M aeiou the set of vowels 0-9 the set of
digits . any single character
41 Finite State Automaton for Identifiers
(S, a2i) (I, 2i) (I, i)
(I, ) (F,
) Thus (S, a2i) (F, )
42Context-Free Grammar
- Production
- a ? ß
- a ? Nonterminal
- ß ? (Nonterminal ? Terminal)
- ie, lefthand side is a single nonterminal, and
righthand side is a string of nonterminals and/or
terminals (possibly empty).
43Context-Sensitive Grammar
- Production
- a ? ß a ß
- a, ß ? (Nonterminal ? Terminal)
- ie, lefthand side can be composed of strings of
terminals and nonterminals, however, the number
of items on the left must be smaller than the
number of items on the right.
44Syntax
- The syntax of a programming language is a precise
description of all its grammatically correct
programs. - Precise syntax was first used with Algol 60, and
has been used ever since. - Three levels
- Lexical syntax - all the basic symbols of the
language (names, values, operators, etc.) - Concrete syntax - rules for writing expressions,
statements and programs. - Abstract syntax - internal representation of the
program, favoring content over form.
45Grammars
- Grammars Metalanguages used to define the
concrete syntax of a language. - Backus Normal Form Backus Naur Form (BNF)
- Stylized version of a context-free grammar (cf.
Chomsky hierarchy) - First used to define syntax of Algol 60
- Now used to define syntax of most major
languages - Production
- a ? ß
- a ? Nonterminal
- ß ? (Nonterminal ? Terminal)
- ie, lefthand side is a single nonterminal, and ß
is a string of nonterminals and/or terminals
(possibly empty). - Example
- Integer ? Digit Integer Digit
- Digit ? 0 1 2 3 4 5 6 7 8 9
46Extended BNF (EBNF)
Additional metacharacters a series of zero
or more ( ) must pick one from a list
pick none or one from a list Example Expression
-gt Term ( - ) Term IfStatement -gt if (
Expression ) Statement else Statement EBNF
is no more powerful than BNF, but its production
rules are often simpler and clearer. Javacc
EBNF ( ) a series of zero or more ( ) a
series of one or more optional
47High Level Overview of Grammar Concepts
a series of zero or more ( ) must pick one
from a list pick none or one from a
list expression -gt term ( - ) term term
-gt factor ( / ) factor factor -gt (
expression ) number // the parenthesis
are part of the grammar not the EBNF number -gt
0 1 2 3 4 5 6 7 8 9
6 ( 11 7 ) / 3 100 ?
48Associativity and Precedence
- A grammar can be used to define associativity and
precedence among the operators in an expression. - E.g., and - are left-associative operators in
mathematics - and / have higher precedence than and - .
- Consider the following grammar
- Expr -gt Expr Term Expr Term Term
- Term -gt Term Factor Term / Factor Term
Factor Factor - Factor -gt Primary Factor Primary
- Primary -gt 0 ... 9 ( Expr )
49Associativity and Precedence
Parse of 423 5 6 7
50 51Runtime Stack for Functions Program
int h, i void B(int w) int j, k
i 2w w w1 void A(int x, int y)
bool i, j B(h) int main()
int a, b h 5 a 3 b 2
A(a, b)
- parameters and local variables
- Return address
- Saved registers
- Temporary variables
- Return value
52with ReL
53ReL Components
CodeCompiler.java
Python.g
AST
Visitor
The Tuple entry in CodeCompiler was modified to
deal with putting SIM, SQL, Prolog, and ASP
information and expressions on the runtime stack
and to assure that a new instance of PyTuple is
created after the expressions are evaluated.
Interpreter
The Python grammar was changed to include SIM,
SQL, Prolog, and ASP statements.
Runtime Stack
PyTuple.java ---------------- parseSIM()
jSQLParser
jSIMParser
jSQLParser parses SQL statements from PyTuple and
produces an AST that can be visited.
There is no jSIMParser to parse SIM statements
like jSQLParser for SQL but I hope one will be
built as a project.
parseSIM parses SIM statements from PyTuple and
produces and passes AS information to SIMHelper.
SIMHelper.java
SQLVisitor.java
SIMHelper produces appropriate SPARQL statements
for the SIM statements which are sent to
SPARQLDoer.
SPARQLDoer.java
SQLVisitor visits the jSQLParser AST and produces
appropriate SPARQL statements for the SQL
statements which are sent to SPARQLDoer.
Oracle DBMS
54What would you expect to find in Jython
- A grammar file for the python language
./grammar/python.g - Java classes that get instantiated as nodes on
the Abstract Syntax Tree - ./src/org/python/antlr/ast
- A way of printing the Abstract Syntax Tree
- ./dist/bin/jython ast/astview.py file.py
- Visitor classes for the interpreter
- ./org/python/antlr/ast/VisitorBase.java
- ./org/python/antlr/ast/VisitorIF.java
- ./org/python/antlr/Visitor.java
- A way to hook into the visitors process of
setting up the runtime stack - ./org/python/compiler/Code.java
- ./org/python/compiler/CodeCompiler.java
- A way to work with the results from the jython
interpreter - an example that well use a lot is
./org/python/core/PyTuple.java
55 cat tests/demo.py dist/bin/jython
ast/astview.py tests/demo.py MAKECONNECT URL
jdbcoraclethin_at_rising-sun.microlab.cs.utexas.ed
u1521orcl UNAME cs345_50 PWORD cs345_50p DROP
TABLE NEWTEST1 CREATE TABLE NEWTEST1 (VAL1
NUMBER, VAL2 NUMBER, VAL3 NUMBER) x3 for i in
2, 4, 7 INSERT INTO NEWTEST1 (VAL1,
VAL2, VAL3) VALUES ((lambda xx1) (4), i, x)
print (SELECT FROM NEWTEST1) print (SELECT
VAL2 FROM NEWTEST1) print (SELECT VAL1, VAL2
FROM NEWTEST1 WHERE VAL3 x) ('Module',
('body', ('Expr (1,0)', ('value',
('Connection (1,0)', ('elts',), ('ctx',
('Load',))))), ('Expr (2,0)', ('value',
('Tuple (2,0)', ('elts',), ('ctx', ('Load',))))),
('Assign (4,0)', ('targets', ('Name
(4,0)', ('id', 'x'), ('ctx', ('Store',)))),
('value', ('Num (4,2)', ('n', 3)))), ('For
(5,0)', ('target', ('Name (5,4)', ('id',
'i'), ('ctx', ('Store',)))), ('iter',
('List (5,9)', ('elts', ('Num
(5,10)', ('n', 2)), ('Num (5,13)', ('n',
4)), ('Num (5,16)', ('n', 7))),
('ctx', ('Load',)))), ('body', ('Expr
(6,1)', ('value', ('Tuple (6,1)',
('elts', ('Call (6,49)',
('func', ('Lambda (6,50)',
('args', ('arguments',
('args', ('Name
(6,57)', ('id', 'x'), ('ctx', ('Param',)))),
('vararg', None),
('body', ('BinOp
(6,59)', ('left',
('Name (6,59)', ('id', 'x'), ('ctx',
('Load',)))), ('op', ('Add',)),
('right', ('Num (6,61)', ('n',
1))))))), ('args', ('Num (6,65)', ('n',
4))), ('keywords',),
('starargs', None), ('kwargs', None)),
('Name (6,69)', ('id', 'i'), ('ctx',
('Load',))), ('Name (6,72)', ('id',
'x'), ('ctx', ('Load',)))), ('ctx',
('Load',)))))), ('orelse',)), ('Print
(7,0)', ('dest', None), ('values',
('Tuple (7,7)', ('elts',), ('ctx', ('Load',)))),
('nl', True)), ('Print (8,0)',
('dest', None), ('values', ('Tuple (8,7)',
('elts',), ('ctx', ('Load',)))), ('nl',
True)), ('Print (9,0)', ('dest', None),
('values', ('Tuple (9,7)',
('elts', ('Name (9,52)', ('id', 'x'), ('ctx',
('Load',)))), ('ctx', ('Load',)))),
('nl', True))))
AST
56MAKECONNECT Python.g
57OWL Inferencing A short Primer
owlFunctionalProperty owlInverseFunctionalProper
ty owlSymmetricProperty owlTransitiveProperty ow
linverseOf
rdfssubClassOf rdfssubPropertyOf rdfsdomain rdf
srange
owlequivalentClass owlequivalentProperty owldis
jointWith owlcomplementOf
owlsameAs owldifferentFrom
owlsomeValuesFrom owlallValuesFrom owlhasValue
58Inference Examples
owlFunctionalProperty owlInverseFunctionalProper
ty owlSymmetricProperty owlTransitiveProperty ow
linverseOf
hasMother rdftype owlFunctionalProperty
John hasMother Mary John
hasMother Maria gt Mary owlsameAs
Maria Maria owlsameAs Mary
59Inference Examples
owlFunctionalProperty owlInverseFunctionalProper
ty owlSymmetricProperty owlTransitiveProperty ow
linverseOf
hasSSN rdftype owlInverseFunctionalProperty
John hasSSN 123-45-6789 Johny
hasSSN 123-45-6789 gt John
owlsameAs Johny Johny owlsameAs John
60Inference Examples
owlFunctionalProperty owlInverseFunctionalProper
ty owlSymmetricProperty owlTransitiveProperty ow
linverseOf
hasSibling rdftype owlSymmetricProperty
John hasSibling Mary gt Mary
hasSibling John
61Inference Examples
owlFunctionalProperty owlInverseFunctionalProper
ty owlSymmetricProperty owlTransitiveProperty ow
linverseOf
hasAncestor rdftype owlTransitiveProperty
John hasAncestor Mary Mary
hasAncestor Tom gt John
hasAncestor Tom
62Inference Examples
owlFunctionalProperty owlInverseFunctionalProper
ty owlSymmetricProperty owlTransitiveProperty ow
linverseOf
hasParent owlinverseOf hasChild
John hasParent Mary gt Mary
hasChild John
63Inference Examples
owlequivalentClass owlequivalentProperty owldis
jointWith owlcomplementOf
Male owldisjointWith Female
John rdftype Male Mary
rdftype Female gt John
owldifferentFrom Mary Mary
owldifferentFrom John
64Inference Examples
owlequivalentClass owlequivalentProperty owldis
jointWith owlcomplementOf
NonHuman owlcomplementOf Human
Fish rdfssubClassOf
NonHuman gt Fish owldisjointWith
Human Human owldisjointWith
Fish
65Semantic Web RDF and RDFS Example
66Semantic Web RDFS and OWL Example
67Semantic Web SQL Type Query
USA
68Semantic Web SPARQL
69OWL Inferencing dont copy this demo from a
PDF, it wont work use the PPT file instead
-- If you dont have an RDS_DATA_TABLE in your
user account, uncomment the following two lines
the first time you run this. -- EXECUTE IMMEDIATE
'CREATE TABLE RDF_DATA_TABLE( id NUMBER, triple
SDO_RDF_TRIPLE_S)' -- SEM_APIS.CREATE_RDF_MODEL('
RDF_MODEL_CS345_PROF1', 'RDF_DATA_TABLE',
'triple') TRUNCATE TABLE "RDF_DATA_TABLE" drop
storage DROP SEQUENCE RDF_DATA_TABLE_SQNC CREATE
SEQUENCE RDF_DATA_TABLE_SQNC START WITH 1
NOCACHE INSERT INTO RDF_DATA_TABLE VALUES (
RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF
_MODEL_CS345_PROF1lthttp//www.example.org/people.
owlgt', 'lthttp//www.example.org/people.owlOBJECT
gt', 'rdftype', 'rdfsClass')) INSERT INTO
RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextva
l, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1lthttp/
/www.example.org/people.owlgt', 'lthttp//www.examp
le.org/people.owlANIMALgt', 'rdftype',
'rdfsClass'))
70OWL Inferencing
INSERT INTO RDF_DATA_TABLE VALUES (
RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF
_MODEL_CS345_PROF1lthttp//www.example.org/people.
owlgt', 'lthttp//www.example.org/people.owlANIMAL
gt', 'rdfssubClassOf', 'lthttp//www.example.org/pe
ople.owlOBJECTgt')) INSERT INTO RDF_DATA_TABLE
VALUES ( RDF_DATA_TABLE_SQNC.nextval,
SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1lthttp//ww
w.example.org/people.owlgt', 'lthttp//www.example.
org/people.owlCATgt', 'rdftype',
'rdfsClass')) INSERT INTO RDF_DATA_TABLE
VALUES ( RDF_DATA_TABLE_SQNC.nextval,
SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1lthttp//ww
w.example.org/people.owlgt', 'lthttp//www.example.
org/people.owlCATgt', 'rdfssubClassOf',
'lthttp//www.example.org/people.owlANIMALgt')) I
NSERT INTO RDF_DATA_TABLE VALUES (
RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF
_MODEL_CS345_PROF1lthttp//www.example.org/people.
owlgt', 'lthttp//www.example.org/people.owli5gt',
'rdftype', 'lthttp//www.example.org/people.owlCA
Tgt')) INSERT INTO RDF_DATA_TABLE VALUES (
RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF
_MODEL_CS345_PROF1lthttp//www.example.org/people.
owlgt', 'lthttp//www.example.org/people.owli5gt',
'lthttp//www.example.org/people.owlvaluegt',
'"101"xsdinteger')) Commit
71OWL Inferencing
-- named graph local inference (NGLI) BEGIN sem_ap
is.create_entailment( 'RDF_ENT_CS345_PROF1',
models_in gt sem_models('RDF_MODEL_CS345_P
ROF1'), rulebases_in gt sem_rulebases('owl2
rl'), passes gt SEM_APIS.REACH_CLOSUR
E, inf_components_in gt null, options
gt 'LOCAL_NG_INFT' ) END /
72OWL Inferencing
select g, s, p, o from table(sem_match('graph
?g ?s ?p ?o', sem_models('RDF_MODEL_CS345_PROF1
'),sem_rulebases('owl2rl'),null,null)) MINUS selec
t g, s, p, o from table(sem_match('graph ?g ?s
?p ?o', sem_models('RDF_MODEL_CS345_PROF1'),null
,null,null)) Returns http//www.example.org/peo
ple.owl http//www.example.org/people.owlCAT http
//www.w3.org/2000/01/rdf-schemasubClassOf
http//www.example.org/people.owlOBJECT
http//www.example.org/people.owl http//www.exam
ple.org/people.owli5 http//www.w3.org/1999/02/22
-rdf-syntax-nstype
http//www.example.org/people.owlANIMAL http//ww
w.example.org/people.owl http//www.example.org/pe
ople.owli5 http//www.w3.org/1999/02/22-rdf-synta
x-nstype http//www.example.org/p
eople.owlOBJECT
73OWL Inferencing
SEM_MODELS('RDF_MODEL_CS345_prof1'),
null, SEM_ALIASES( SEM_ALIAS('',
'http//www.example.org/people.owl')), null)
) SELECT value from table( sem_match('select
where ?indiv rdftype CAT. ?indiv value
?value . ', SEM_MODELS('RDF_MODEL_CS345_prof1'),
sem_rulebases('owl2rl'), SEM_ALIASES(
SEM_ALIAS('', 'http//www.example.org/people.owl'
)), null) ) Returns Value 101
74OWL Inferencing
SEM_MODELS('RDF_MODEL_CS345_prof1'),
null, SEM_ALIASES( SEM_ALIAS('',
'http//www.example.org/people.owl')), null)
) SELECT value from table( sem_match('select
where ?indiv rdftype ANIMAL. ?indiv
value ?value . ', SEM_MODELS('RDF_MODEL_CS345_pr
of1'), sem_rulebases('owl2rl'), SEM_ALIASES(
SEM_ALIAS('', 'http//www.example.org/people.owl'
)), null) ) Returns Value 101
75OWL Inferencing
SEM_MODELS('RDF_MODEL_CS345_prof1'),
null, SEM_ALIASES( SEM_ALIAS('',
'http//www.example.org/people.owl')), null)
) SELECT value from table( sem_match('select
where ?indiv rdftype OBJECT. ?indiv
value ?value . ', SEM_MODELS('RDF_MODEL_CS345_pr
of1'), sem_rulebases('owl2rl'), SEM_ALIASES(
SEM_ALIAS('', 'http//www.example.org/people.owl'
)), null) ) Returns Value 101
76Initial Concepts for
77Proof by Contradiction
P1 P2
1). Let P Its raining, Im outside (comma
means ) 2). P1. (P1 is True, i.e., its
raining) 3). P2. (P2 is True, i.e., Im
outside) 4). Q - P Im wet - Its raining,
Im outside. (if its raining and Im
outside then Im wet) 5). Q (To answer the
Query Am I wet against the Database, assume Im
not wet) 6). (Its raining, Im outside)
( From 4 and 5 and Pattern 1 ) 7). Im
outside
( From 2 and 6 and Pattern 2 ) 8). Contradiction
Therefore Im wet ( From 3 and 7 and
Pattern 3 )
Facts
Rule
Pattern 1 (Modus Tollens) Q - (P1, P2). -Q ?
-(P1, P2) Pattern 2 (Affirming a
Conjunct) P1. -(P1, P2) ? -P2 Pattern
3 P2. -P2 ? Contradiction
Database
P
R
S
78Proof by Contradiction
- A is an Animal.
- A Barks.
- A is a Dog - A is an Animal, A Barks.
- -(A is a Dog)
- 3 and 4 and Pattern 1 ? -(A is an Animal, A
Barks) - 1 and 5 and Pattern 2 ? -A Barks
- 2 and 6 and Pattern 3 ? Contradiction
- Therefore A is a Dog
Database
Query (If you want to know if A is a Dog based
upon the Facts and Rules in the Database try to
see if A is not a Dog.)