Download presentation
Presentation is loading. Please wait.
Published byAnthony Fowler Modified over 9 years ago
1
Dr. Philip Cannata 1 Programming Languages Syllogisms and Proof by Contradiction Midterm Review
2
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.
3
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
4
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.
5
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 Database FactsRule 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
6
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.)
7
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".propositions Thought, expressed in language, "pictures" these facts. Tractatus
8
Dr. Philip Cannata 8 Previous Midterm Exam
9
Dr. Philip Cannata 9 Study All the Homework and Quizzes
10
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:,,,,, 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)
11
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
12
Dr. Philip Cannata 12
13
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
14
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
15
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)
16
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)
17
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)
18
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)
19
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)
20
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
21
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. x 2 ) 5) = 5 2
22
Dr. Philip Cannata 22 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)
23
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)
24
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
25
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)))
26
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")]))
27
Dr. Philip Cannata 27 Functions and Recursion
28
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)
29
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))))))
30
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 (cons 1 || (cons 2 || (cons 3 || (cons 4 || (cons 5 || (cons 5 '())))))) This can be thought of as a stack with “cons”s on it. Here the stack is upside down
31
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 Nothing goes on the stack in this case.
32
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.
33
Dr. Philip Cannata 33 A Different Road to High-level Languages
34
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
35
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" | } TOKEN: { | } TOKEN: /* Literals */ { } TOKEN: { } void ae() : { Token n; } { n = { System.out.print("(num " + n +")"); } | list() } void list() : {} { LOOKAHEAD(2) { System.out.print(" (add ");} ( ae() )* { System.out.print(") "); } | { System.out.print(" (sub ");} ( ae() )* { System.out.print(") "); } } Parser Grammar Production Rules Tokens, Terminals Syntax and Grammar – Parser.jj
36
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" | } TOKEN: { | } TOKEN: /* Literals */ { < IDENTIFIER: [ "A"-"Z", "a"-"z" ] ( [ "A"-"Z", "a"-"z", "0"-"9", "_"] )* > } TOKEN: { } void program() : { } { ( rels() )+ ( comps() )* } void rels() : { String id; } { ( id = identifier() { System.out.println(" Saw IDENTIFIER " + id); } )+ { System.out.println("Saw a RELATION"); } } String identifier() : { Token t; } { t = { return new String(t.image); } } void comps() : { String id1, id2; } { id1 = identifier() id2 = identifier() { System.out.println("Saw Composiiton of " + id1 + " with " + id2); } } Example Javacc Parser
37
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
38
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
39
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
40
Dr. Philip Cannata 40 Regular Expressions xa character x \xan escaped character, e.g., \n { name }a reference to a name M | NM or N M NM 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
Dr. Philip Cannata 41 (S, a2i$) ├ (I, 2i$) ├ (I, i$) ├ (I, $) ├ (F, ) Thus: (S, a2i$) ├* (F, ) Finite State Automaton for Identifiers
42
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
43
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
44
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
45
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).nonterminalterminals Example Integer Digit | Integer Digit Digit 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
46
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
47
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
48
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
49
Dr. Philip Cannata 49 Associativity and Precedence Parse of 4**2**3 + 5 * 6 + 7
50
Dr. Philip Cannata 50 Functions and Recursion
51
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
52
Dr. Philip Cannata 52 with ReL
53
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.
54
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
55
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),jdbc:oracle:thin:@rising-sun.microlab.cs.utexas.edu:1521:orcl AST
56
Dr. Philip Cannata 56 MAKECONNECT– Python.g
57
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
58
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
59
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
60
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
61
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
62
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
63
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
64
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
65
Dr. Philip Cannata 65 Semantic Web – RDF and RDFS Example
66
Dr. Philip Cannata 66 Semantic Web – RDFS and OWL Example
67
Dr. Philip Cannata 67 Semantic Web – SQL Type Query USA
68
Dr. Philip Cannata 68 Semantic Web – SPARQL
69
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: ', ' ', 'rdf:type', 'rdfs:Class')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1: ', ' ', 'rdf:type', 'rdfs:Class'));
70
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: ', ' ', 'rdfs:subClassOf', ' ')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1: ', ' ', 'rdf:type', 'rdfs:Class')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1: ', ' ', 'rdfs:subClassOf', ' ')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1: ', ' ', 'rdf:type', ' ')); INSERT INTO RDF_DATA_TABLE VALUES ( RDF_DATA_TABLE_SQNC.nextval, SDO_RDF_TRIPLE_S('RDF_MODEL_CS345_PROF1: ', ' ', ' ', '"101"^^xsd:integer')); Commit;
71
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; /
72
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.owlhttp://www.example.org/people.owl#CAT http://www.w3.org/2000/01/rdf-schema#subClassOf http://www.w3.org/2000/01/rdf-schema#subClassOf http://www.example.org/people.owl#OBJECT http://www.example.org/people.owlhttp://www.example.org/people.owl#i5 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.example.org/people.owl#ANIMAL http://www.example.org/people.owlhttp://www.example.org/people.owl#i5 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.example.org/people.owl#OBJECT
73
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
74
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
75
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
76
Dr. Philip Cannata 76 Initial Concepts for
77
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 Database FactsRule 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
78
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.)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.