Dr. Philip Cannata 1
Programming Languages!
• Syllogisms and Proof by Contradiction
• Midterm Review
Dr. Philip Cannata 2
Truth: Are there well formed propositional formulas (i.e., Statements) that return True when their input is True truth1 :: (Bool -> Bool) -> Bool truth1 wff = (wff True) truth2 :: (Bool -> Bool -> Bool) -> Bool truth2 wff = (wff True True)
( \ p -> not p)
( \ p q -> (p && q) || (not p ==> q))
( \ p q -> not p ==> q)
( \ p q -> (not p && q) && (not p ==> q) )
Propositions: Statements that can be either True or False
Notions of Truth
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.
Dr. Philip Cannata 3
è Contradiction Therefore A is a Dog
Proof by Contradiction
1. A is an Animal.
2. A Barks. 3. A is a Dog :- A is an Animal, A Barks. (A is a Dog IF A is and Animal AND A Barks) :- ,
4. -(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.)
Can this reasoning be automated?
Facts
Rule
Dr. Philip Cannata 4
Syllogisms
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.
Syllogism – e.g., Modus Ponens – 1). P is True; 2). P à Q is True, therefore Q is True.
P implies Q (i.e., Q is True if P is True or If P is True then Q is True)
Note: this is Prolog notation. In “standard” notation, this would be P à Q.
Dr. Philip Cannata 5
1). Let P = It’s raining, I’m outside (comma means “&&”) 2). P1. (P1 is True, i.e., it’s raining) 3). P2. (P2 is True, i.e., I’m outside) 4). Q :- P = I’m wet :- It’s raining, I’m outside. (if it’s raining and I’m outside then I’m wet) 5). –Q (To answer the Query “Am I wet” against the Database, assume I’m not wet) 6). –(It’s raining, I’m outside) ( From 4 and 5 and Pattern 1 ) 7). –I’m outside ( From 2 and 6 and Pattern 2 ) 8). Contradiction – Therefore I’m wet ( From 3 and 7 and Pattern 3 )
Proof by Contradiction P1 P2
Dat
abas
e
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
P
R
S
Dr. Philip Cannata 6
Proof by Contradiction
1. A is an Animal.
2. A Barks.
3. A is a Dog :- A is an Animal, A Barks.
4. -(A is a Dog)
5. 3 and 4 and Pattern 1 è -(A is an Animal, A Barks)
6. 1 and 5 and Pattern 2 è -A Barks
7. 2 and 6 and Pattern 3 è Contradiction
8. 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.)
Dr. Philip Cannata 7
Midterm Review
What we cannot speak about we must pass over in silence. • The world consists of independent atomic facts—existing states of affairs—out 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
Dr. Philip Cannata 10
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: <S>, <K>, <B>, <C>, <Y>, 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.)
Functional Programming (Relation Programming) Universe (Concepts for building a lisp interpreter)
Dr. Philip Cannata 11
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
High Level Language Universe (Concepts for building a HLL interpreter like ReL)
Tools javacc / JJTree / JTB / JJDoc o Antlr ant SQLDeveloper jDeveloper or Eclipse jSQLParser
Dr. Philip Cannata 13
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 function’s arguments and the last element is the function’s results and whenever R is given the same set of arguments, it always returns the same results. [Notice, this is an unnamed function!].
Relations and Functions
Dr. Philip Cannata 14
Function 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 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.
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.
Thoralf Skolem
Dr. Philip Cannata 15
• 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).
Primitive Recursive Functions and Arithmetic (see “A Profile of Mathematical Logic” by Howard Delong – pages 152 – 160)
Dr. Philip Cannata 16
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)’)
=> (0’’ 0’ (0’’)’) => (0’’ 0’ 0’’’) 2 + 1 = 3
(0’’ 0’’ (0’’ 0’ b)’)
=> (0’’ 0’’ (0’’’)’) => (0’’ 0’’ 0’’’’) 2 + 2 = 4
• (0’’ 0’’’ (0’’ 0’’ b)’)
• => (0’’ 0’’’ (0’’’’)’) => (0’’ 0’’’ 0’’’’’) 2 + 3 = 5
Primitive Recursive Functions and Arithmetic (see “A Profile of Mathematical Logic” by Howard Delong – pages 152 – 160)
Dr. Philip Cannata 17
“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]
Primitive Recursive Functions and Arithmetic (see “A Profile of Mathematical Logic” by Howard Delong – pages 152 – 160)
Dr. Philip Cannata 18
A Sequence of Functions from definitions on DeLong, page 157:
Primitive Recursive Functions and Arithmetic (see “A Profile of Mathematical Logic” by Howard Delong – pages 152 – 160)
Book notation Relation notation Arithmetic notation f1(x) = x’ (x (+ x 1)) f1 is the successor
function f2(x) = x (x x) f2 is the identity
function with i = 1 f3(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))) f4 is defined by
substitution for f1 and f3
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)))
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 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))))
Dr. Philip Cannata 19
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))
Primitive Recursive Functions and Arithmetic (see “A Profile of Mathematical Logic” by Howard Delong – pages 152 – 160)
Dr. Philip Cannata 20
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.
A little Bit of Lambda Calculus – Lambda Expressions
Dr. Philip Cannata 21
A 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 M[x ← 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
Dr. Philip Cannata 22
Lambda 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 true=select_first !def false=select_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)!
Dr. Philip Cannata 23
Lambda 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)
Dr. Philip Cannata 24
(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)))))) ) (map factorial (list 4 1 2 3 5))) à (list 24 1 2 6 120)
Define statement:
(define nth (lambda (N List) (if (not (= N 0))(nth (- N 1) (cdr List))(car List)))) (nth 2 (list 1 2 3 4 5)) à 3
Simple Lisp in Scheme
Dr. Philip Cannata 25
Develop 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)))
Dr. Philip Cannata 26
Scheme 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")]))
Dr. Philip Cannata 28
“let” 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)
Dr. Philip Cannata 29
Static 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))))))
Dr. Philip Cannata 30
(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.
It‘s the same as
(cons 1 (cons 2 (cons 3( cons 4 (cons 5 (cons 6 '()))))))
Recursive Functions Exemplified by foldr in lisp (c
ons 1
|| (c
ons 2
|| (c
ons 3
|| (c
ons 4
|| (c
ons 5
|| (c
ons 5
'())
))))
) (cons 1 || (cons 2 || (cons 3 || (cons 4 || (cons 5 || (cons 5 '()))))))
This
can
be
thou
ght o
f as a
stac
k w
ith “
cons
”s o
n it.
H
ere the stack is upside down
Dr. Philip Cannata 31
(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.
It‘s the same as
(cons 6 (cons 5 (cons 4 ( cons 3 (cons 2 (cons 1 '()))))))
Recursive Functions Exemplified by foldl in lisp N
othi
ng g
oes o
n th
e st
ack
in th
is c
ase.
Dr. Philip Cannata 32
PLAI Chapters 4, 5 and 6
Page 27 - "
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.
Dr. Philip Cannata 34
Abstract Syntax
Internal Parse Tree
int main ()
{
return 0 ;
}
Program (abstract syntax): Function = main; Return type = int params = Block: Return: Variable: return#main, LOCAL addr=0 IntValue: 0
Instance of a Programming Language:
We’ll be starting with javacc à moving to ANTLR later
Dr. Philip Cannata 35
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" | <"//" (~["\n","\r"])* ("\n"|"\r")> } TOKEN: { < LCURLY: "{" > | < RCURLY: "}" > | < MINUS: "-" > | < PLUS: "+" > } TOKEN: /* Literals */ { < INTEGER: (["0"-"9"])+ > } TOKEN: { <ERROR: ~[] > }
void ae() : { Token n; } { n = <INTEGER> { System.out.print("(num " + n +")"); } | list() } void list() : {} { LOOKAHEAD(2) <LCURLY> <PLUS> { System.out.print(" (add ");}
( ae() )* <RCURLY> { System.out.print(") "); } | <LCURLY> <MINUS> { System.out.print(" (sub ");} ( ae() )*
<RCURLY> { System.out.print(") "); } }
Parser
Grammar Production Rules
Tokens, Terminals
Syntax and Grammar – Parser.jj
Dr. Philip Cannata 36
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" | <"//" (~["\n","\r"])* ("\n"|"\r")> } TOKEN: { < RELATION: "Relation" > | < COMPOSE: "Compose" > | < WITH: "with" > } TOKEN: /* Literals */ { < IDENTIFIER: [ "A"-"Z", "a"-"z" ] ( [ "A"-"Z", "a"-"z", "0"-"9", "_"] )* > } TOKEN: { <ERROR: ~[] > }
void program() : { } { ( rels() )+ ( comps() )* } void rels() : { String id; } { <RELATION> ( id = identifier() { System.out.println(" Saw IDENTIFIER " + id); } )+ { System.out.println("Saw a RELATION"); } } String identifier() : { Token t; } { t = <IDENTIFIER> { return new String(t.image); } } void comps() : { String id1, id2; } { <COMPOSE> id1 = identifier() <WITH> id2 = identifier() { System.out.println("Saw Composiiton of " + id1 + " with " + id2); } }
Example Javacc Parser
Dr. Philip Cannata 37
• Regular grammar – used for tokenizing • Context-free grammar (BNF) – used for parsing • Context-sensitive grammar – not really used for
programming languages
Chomsky Hierarchy
Dr. Philip Cannata 38
• 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
Regular Grammar
Dr. Philip Cannata 39
• Less powerful than context-free grammars • The following is not a regular language
{ aⁿ bⁿ | n ≥ 1 } i.e., cannot balance: ( ), { }, begin end
Regular Grammar
Dr. Philip Cannata 40
Regular 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
Dr. Philip Cannata 41
!
(S, a2i$) ├ (I, 2i$) ├ (I, i$) ├ (I, $)
├ (F, )
Thus: (S, a2i$) ├* (F, )
Finite State Automaton for Identifiers
Dr. Philip Cannata 42
Production: α → β α ∈ Nonterminal
β ∈ (Nonterminal ∪ Terminal)*
ie, lefthand side is a single nonterminal, and righthand side is a string of nonterminals and/or terminals (possibly empty).
Context-Free Grammar
Dr. Philip Cannata 43
Production: α → β |α| ≤ |β| α, β ∈ (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.
Context-Sensitive Grammar
Dr. Philip Cannata 44
• 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.
Syntax
Dr. Philip Cannata 45
Grammars 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: α → β α ∈ 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
Dr. Philip Cannata 46
Extended 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 -> Term { ( + | - ) Term } IfStatement -> 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
Dr. Philip Cannata 47
{ } a series of zero or more ( ) must pick one from a list [ ] pick none or one from a list expression -> term { ( + | - ) term } term -> factor { ( * | / ) factor } factor -> ( expression ) | number // the parenthesis are part of the grammar not the EBNF number -> { 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 } 6 * ( 11 – 7 ) / 3 + 100 è
High Level Overview of Grammar Concepts
Dr. Philip Cannata 48
• 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 -> Expr + Term | Expr – Term | Term Term -> Term * Factor | Term / Factor | Term % Factor | Factor Factor -> Primary ** Factor | Primary Primary -> 0 | ... | 9 | ( Expr )
Associativity and Precedence
Dr. Philip Cannata 51
int h, i;!void B(int w) {! int j, k;! i = 2*w;! w = w+1;!} !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
Runtime Stack for Functions Program
Dr. Philip Cannata 53
ReL Components
Python.g
SPARQLDoer.java
PyTuple.java ---------------- parseSIM()
AST
Runtime Stack
SIMHelper.java
Visitor
SQLVisitor.java
jSQLParser
Interpreter
Oracle DBMS
jSIMParser
CodeCompiler.java
The Python grammar was changed to include SIM, SQL, Prolog, and ASP statements.
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.
jSQLParser parses SQL statements from PyTuple and produces an AST that can be visited.
SQLVisitor visits the jSQLParser AST and produces appropriate SPARQL statements for the SQL statements which are sent to SPARQLDoer.
parseSIM parses SIM statements from PyTuple and produces and passes AS information to SIMHelper.
SIMHelper produces appropriate SPARQL statements for the SIM statements which are sent to SPARQLDoer.
There is no jSIMParser to parse SIM statements like jSQLParser for SQL but I hope one will be built as a project.
Dr. Philip Cannata 54
• 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 visitor’s 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 we’ll use a lot is ./org/python/core/PyTuple.java
What would you expect to find in Jython
Dr. Philip Cannata 55
('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))))
$ cat tests/demo.py ; dist/bin/jython ast/astview.py tests/demo.py MAKECONNECT URL jdbc:oracle:thin:@rising-sun.microlab.cs.utexas.edu:1521:orcl UNAME cs345_50 PWORD cs345_50p; DROP TABLE NEWTEST1; # CREATE TABLE NEWTEST1 (VAL1 NUMBER, VAL2 NUMBER, VAL3 NUMBER); x=3 for i in [2, 4, 7]: INSERT INTO NEWTEST1 (VAL1, VAL2, VAL3) VALUES ((lambda x:x+1) (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),
AST
Dr. Philip Cannata 57
OWL Inferencing: A short Primer!
rdfs:subClassOf
rdfs:subPropertyOf
rdfs:domain
rdfs:range
owl:FunctionalProperty
owl:InverseFunctionalProperty
owl:SymmetricProperty
owl:TransitiveProperty
owl:inverseOf
owl:someValuesFrom
owl:allValuesFrom
owl:hasValue
owl:sameAs
owl:differentFrom
owl:equivalentClass
owl:equivalentProperty
owl:disjointWith
owl:complementOf
Dr. Philip Cannata 58
Inference: Examples!owl:FunctionalProperty
owl:InverseFunctionalProperty
owl:SymmetricProperty
owl:TransitiveProperty
owl:inverseOf
:hasMother rdf:type owl:FunctionalProperty
:John :hasMother :Mary :John :hasMother :Maria => :Mary owl:sameAs :Maria :Maria owl:sameAs :Mary
Dr. Philip Cannata 59
Inference: Examples!owl:FunctionalProperty
owl:InverseFunctionalProperty
owl:SymmetricProperty
owl:TransitiveProperty
owl:inverseOf
:hasSSN rdf:type owl:InverseFunctionalProperty
:John :hasSSN 123-45-6789 :Johny :hasSSN 123-45-6789 => :John owl:sameAs :Johny :Johny owl:sameAs :John
Dr. Philip Cannata 60
Inference: Examples!owl:FunctionalProperty
owl:InverseFunctionalProperty
owl:SymmetricProperty
owl:TransitiveProperty
owl:inverseOf
:hasSibling rdf:type owl:SymmetricProperty :John :hasSibling :Mary => :Mary :hasSibling :John
Dr. Philip Cannata 61
Inference: Examples!owl:FunctionalProperty
owl:InverseFunctionalProperty
owl:SymmetricProperty
owl:TransitiveProperty
owl:inverseOf
:hasAncestor rdf:type owl:TransitiveProperty :John :hasAncestor :Mary :Mary :hasAncestor :Tom => :John :hasAncestor :Tom
Dr. Philip Cannata 62
Inference: Examples!owl:FunctionalProperty
owl:InverseFunctionalProperty
owl:SymmetricProperty
owl:TransitiveProperty
owl:inverseOf
:hasParent owl:inverseOf :hasChild :John :hasParent :Mary => :Mary :hasChild :John
Dr. Philip Cannata 63
Inference: Examples!
:Male owl:disjointWith :Female
owl:equivalentClass
owl:equivalentProperty
owl:disjointWith
owl:complementOf
:John rdf:type :Male :Mary rdf:type :Female => :John owl:differentFrom :Mary :Mary owl:differentFrom :John
Dr. Philip Cannata 64
Inference: Examples!
:NonHuman owl:complementOf :Human
owl:equivalentClass
owl:equivalentProperty
owl:disjointWith
owl:complementOf
:Fish rdfs:subClassOf :NonHuman => :Fish owl:disjointWith :Human :Human owl:disjointWith :Fish
Dr. Philip Cannata 69
OWL Inferencing – don’t copy this demo from a PDF, it won’t work – use the PPT file instead
-- If you don’t 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_PROF1:<http://www.example.org/people.owl>', '<http://www.example.org/people.owl#OBJECT>', 'rdf:type', 'rdfs:Class')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1:<http://www.example.org/people.owl>', '<http://www.example.org/people.owl#ANIMAL>', 'rdf:type', 'rdfs:Class'));
Dr. Philip Cannata 70
OWL Inferencing INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1:<http://www.example.org/people.owl>', '<http://www.example.org/people.owl#ANIMAL>', 'rdfs:subClassOf', '<http://www.example.org/people.owl#OBJECT>')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1:<http://www.example.org/people.owl>', '<http://www.example.org/people.owl#CAT>', 'rdf:type', 'rdfs:Class')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1:<http://www.example.org/people.owl>', '<http://www.example.org/people.owl#CAT>', 'rdfs:subClassOf', '<http://www.example.org/people.owl#ANIMAL>')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1:<http://www.example.org/people.owl>', '<http://www.example.org/people.owl#i5>', 'rdf:type', '<http://www.example.org/people.owl#CAT>')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1:<http://www.example.org/people.owl>', '<http://www.example.org/people.owl#i5>', '<http://www.example.org/people.owl#value>', '"101"^^xsd:integer')); Commit;
Dr. Philip Cannata 71
OWL Inferencing -- named graph local inference (NGLI) BEGIN sem_apis.create_entailment( 'RDF_ENT_CS345_PROF1', models_in => sem_models('RDF_MODEL_CS345_PROF1'), rulebases_in => sem_rulebases('owl2rl'), passes => SEM_APIS.REACH_CLOSURE, inf_components_in => null, options => 'LOCAL_NG_INF=T' ); END; /
Dr. Philip Cannata 72
OWL 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 select 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/people.owl http://www.example.org/people.owl#CAT
http://www.w3.org/2000/01/rdf-schema#subClassOf http://www.example.org/people.owl#OBJECT http://www.example.org/people.owl http://www.example.org/people.owl#i5
http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.example.org/people.owl#ANIMAL http://www.example.org/people.owl http://www.example.org/people.owl#i5
http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.example.org/people.owl#OBJECT
Dr. Philip Cannata 73
OWL 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 rdf:type :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
Dr. Philip Cannata 74
OWL 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 rdf:type :ANIMAL. ?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
Dr. Philip Cannata 75
OWL 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 rdf:type :OBJECT. ?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
Dr. Philip Cannata 77
1). Let P = It’s raining, I’m outside (comma means “&&”) 2). P1. (P1 is True, i.e., it’s raining) 3). P2. (P2 is True, i.e., I’m outside) 4). Q :- P = I’m wet :- It’s raining, I’m outside. (if it’s raining and I’m outside then I’m wet) 5). –Q (To answer the Query “Am I wet” against the Database, assume I’m not wet) 6). –(It’s raining, I’m outside) ( From 4 and 5 and Pattern 1 ) 7). –I’m outside ( From 2 and 6 and Pattern 2 ) 8). Contradiction – Therefore I’m wet ( From 3 and 7 and Pattern 3 )
Proof by Contradiction P1 P2
Dat
abas
e
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
P
R
S
Dr. Philip Cannata 78
Proof by Contradiction
1. A is an Animal.
2. A Barks.
3. A is a Dog :- A is an Animal, A Barks.
4. -(A is a Dog)
5. 3 and 4 and Pattern 1 è -(A is an Animal, A Barks)
6. 1 and 5 and Pattern 2 è -A Barks
7. 2 and 6 and Pattern 3 è Contradiction
8. 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.)