1 Lecture 6 Logic Programming rule-based programming with Prolog Ras Bodik with Mangpo, Ali Hack Your Language! CS164: Introduction to Programming Languages.

Slides:



Advertisements
Similar presentations
Artificial Intelligence: Natural Language and Prolog
Advertisements

First Order Logic Logic is a mathematical attempt to formalize the way we think. First-order predicate calculus was created in an attempt to mechanize.
SLD-resolution Introduction Most general unifiers SLD-resolution
Semantics Static semantics Dynamic semantics attribute grammars
Chapter 11 :: Logic Languages
Prolog The language of logic. History Kowalski: late 60’s Logician who showed logical proof can support computation. Colmerauer: early 70’s Developed.
Prolog.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/5.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/8.
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been reproduced and communicated to you by or on behalf of Monash University.
Prolog The language of logic. History Kowalski: late 60’s Logician who showed logical proof can support computation. Colmerauer: early 70’s Developed.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
1 Logic Programming. 2 A little bit of Prolog Objects and relations between objects Facts and rules. Upper case are variables. parent(pam, bob).parent(tom,bob).
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter 12 - Logic Programming
Chapter 8: The Logical Paradigm Lecturer: Xinming (Simon) Ou CIS 505: Programming Languages Fall 2010 Kansas State University 1.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Constraint Logic Programming Ryan Kinworthy. Overview Introduction Logic Programming LP as a constraint programming language Constraint Logic Programming.
Comp 205: Comparative Programming Languages Declarative Programming Languages Unification Backtracking Lecture notes, exercises, etc., can be found at:
PPL Syntax & Formal Semantics Lecture Notes: Chapter 2.
Formal Models of Computation Part II The Logic Model
Notes for Chapter 12 Logic Programming The AI War Basic Concepts of Logic Programming Prolog Review questions.
1 Lecture 7 Implementing Prolog unification, backtracking with coroutines Ras Bodik Shaon Barman Thibaud Hottelier Hack Your Language! CS164: Introduction.
Propositional Calculus Composed of symbols –P – some true statement P might represent something like “It is Monday” or “the car is red” And sentences –a.
1-1 Introduction Logic programming languages, sometimes called declarative programming languages Express programs in a form of symbolic logic Use a logical.
1 Lecture 7 Implementing Prolog unification, backtracking with coroutines Ras Bodik with Mangpo and Ali Hack Your Language! CS164: Introduction to Programming.
1 Lecture 6 Logic Programming introduction to Prolog, facts, rules Ras Bodik Shaon Barman Thibaud Hottelier Hack Your Language! CS164: Introduction to.
Cs7120 (Prasad)L16-Meaning1 Procedural and Declarative Meaning of Prolog
CS Describing Syntax CS 3360 Spring 2012 Sec Adapted from Addison Wesley’s lecture notes (Copyright © 2004 Pearson Addison Wesley)
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
F28PL1 Programming Languages Lecture 16: Prolog 1.
Logic Programming Module 2AIT202 Website Lecturer: Dave Sharp Room: AG15
Artificial Intelligence Programming in Prolog Lecture 1: An Introduction 23/09/04.
1.  Provides the ability to access individual assertions. e.g. in Predicate calculus we may say: P denotes “It rained on Tuesday” but in predicate calculus.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now Chapter 9, exs 4 and 6. –6 must be in Horn clause form Prolog Handout 2.
Introduction To PROLOG World view of imperative languages. World view of relational languages. A PROLOG program. Running a PROLOG program. A PROLOG.
CS Introduction to AI Tutorial 8 Resolution Tutorial 8 Resolution.
CS 603: Programming Languages Lecture 25 Spring 2004 Department of Computer Science University of Alabama Joel Jones.
Prolog Kyle Marcotte. Outline What is Prolog? Origins of Prolog (History) Basic Tutorial TEST!!! (sort of…actually not really at all) My example Why Prolog?
Lecture 9b: Prolog Heshaam Faili University of Tehran The language of logic Concepts Examples.
Dr. Muhammed Al-Mulhem ICS An Introduction to Logical Programming.
Logic Programming Languages Session 13 Course : T Programming Language Concept Year : February 2011.
603 Database Systems Senior Lecturer: Laurie Webster II, M.S.S.E.,M.S.E.E., M.S.BME, Ph.D., P.E. Lecture 24 A First Course in Database Systems.
603 Database Systems Senior Lecturer: Laurie Webster II, M.S.S.E.,M.S.E.E., M.S.BME, Ph.D., P.E. Lecture 25 A First Course in Database Systems.
For Monday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Introduction to Prolog. Outline What is Prolog? Prolog basics Prolog Demo Syntax: –Atoms and Variables –Complex Terms –Facts & Queries –Rules Examples.
CS 337 Programming Languages Logic Programming I (Logic, Intro to Prolog)
© Kenneth C. Louden, Chapter 12 - Logic Programming Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
Propositional Logic Predicate Logic
Logic Programming Dr. Yasser Ahmed Nada Fall 2010/2011 Lecture 2 1 Logic Programming.
CS 403: Programming Languages Lecture 18 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
CS 152: Programming Language Paradigms March 12 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Programming Language Concepts Lecture 17 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Logic Programming.
MB: 26 Feb 2001CS Lecture 11 Introduction Reading: Read Chapter 1 of Bratko Programming in Logic: Prolog.
C. Varela1 Logic Programming (PLP 11, CTM 9.1) Terms, Resolution, Unification, Search, Backtracking (Prolog) Relational Computation Model (Oz) Carlos Varela.
CS412/413 Introduction to Compilers Radu Rugina Lecture 13 : Static Semantics 18 Feb 02.
Knowledge Based Information System
1-1 An Introduction to Logical Programming Sept
For Friday No reading Prolog Handout 2. Homework.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
Introduction to Prolog Asst. Prof. Dr. Senem Kumova Metin Revised lecture notes of “Concepts of Programmig Languages, Robert W. Sebesta, Ch. 16”
Pengenalan Prolog Disampaikan Oleh : Yusuf Nurrachman, ST, MMSI.
Section 16.5, 16.6 plus other references
By P. S. Suryateja Asst. Professor, CSE Vishnu Institute of Technology
Carlos Varela Rennselaer Polytechnic Institute November 11, 2016
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
Carlos Varela Rensselaer Polytechnic Institute November 14, 2017
Prolog syntax + Unification
Chapter 2: Prolog (Introduction and Basic Concepts)
Presentation transcript:

1 Lecture 6 Logic Programming rule-based programming with Prolog Ras Bodik with Mangpo, Ali Hack Your Language! CS164: Introduction to Programming Languages and Compilers, Spring 2013 UC Berkeley

Today Why study Prolog -our abstraction stack Introduction to Prolog -facts and queries -generalization, instantiation, and the Prolog semantics -rules -functors: AST and a simple interpreter -working with lists -a simple AST rewrite engine 2

Reading Compulsory: Adventures in PrologAdventures in Prolog, a tutorial (Chapters 1-11) Optional: The Art of Prolog, on reserve in Engineering Library (starting Friday evening, Feb 8). 3

Why logic programming? 4

Our abstraction stack Parsing (PA4), Analysis of Programs, Types –we’ll express each with Prolog rules –(not all will require backtracking) Logic programming (PA3) -a convenient layer over backtracking -enables rule-based programming, inference Coroutines (PA2) -enable lazy iterators and backtracking -ex: regex matching: for all matches of patt1, match patt2 Closures and lexical scoping (PA1) –enable, for example, iterators –ex: d3.select(someNodes).each(aClosure) 5

Infrastructure 6

Software Software: install SWI PrologSWI Prolog Usage: ?- [likes]. # loads file likes.pl Content of file likes.pl: likes(john,mary). likes(mary,jim). After loading, we can ask a query: ?- likes(X,mary). #who likes mary? X = john ; # type semicolon to ask “who else?” false. # no one else 7

Facts, queries, and variables 8

Facts and queries (Database of) two facts: likes(john, mary). # relation: facts with same name, eg likes likes(mary, jim). # relation is a.k.a. predicate Boolean queries (answers are true or false) ?- likes(john,jim). # sometimes we use syntax likes(a,b)? false Existential queries (is there X s/t likes(X,jim) holds?) ?- likes(X,jim). # variables start with capital letters mary# atoms start with capital letters 9

goals, facts, and queries Syntactically, facts and queries look similar goal: likes(jim, mary) notice that there is no dot at the end of goal fact: likes(jim, mary). states that the goal likes(jim,mary) is true query: likes(jim, mary)? sometimes we write ?- goal. asks whether the goal likes(jim, mary) is true 10

Terminology Ground terms (do not contain variables) father(a,b).# fact (a is father of b) ?- father(a,b).# query (is a father of b?) Non-ground terms (contain variables) likes(X,X).# fact: everyone likes himself ?- likes(Y,mary).# query: who likes mary? Variables in facts are universally quantified for whatever X, it is true that X likes X Variables in queries are existentially quantified does there exist an X such that X likes mary? 11

Example A single fact likes(X,X). Queries: ?- likes(a,b). false. ?- likes(a,a). true. ?- likes(X,a). X = a. ?- likes(X,Y). X = Y. <-- Answers to queries need not be fully grounded ?- likes(A,A). true. 12

Generalization and Deduction via Substitution for Variables 13

Generalization (a deduction rule) Facts father(abraham,isaac). Query ?- father(abraham,X). This query is a generalization of the fact We answer the query by finding a substitution {X=isaac}. This substitution turns the query into a fact that exists in the database, leading to true. Well, the answer also shows the substitution. 14

Instantiation (another deduction rule) Rather than writing plus(0,1,1). plus(0,2,2). … We write plus(0,X,X).# 0+x=x plus(X,0,X).# x+0=x Query ?- plus(0,3,3). # this query is instantiation of plus(0,X,X). yes We answer by finding a substitution {X=3}. 15

Prolog semantics How the Prolog interpreter answers a query: p(a,a). # fact 1 p(a,b). # fact 2 p(b,c). # fact 3 ?- p(a,A). # This query raises one goal, p(a,A) A = a ; # going top down across facts, the goal matches 1 A = b. # and when asked for next match, it matches 2. We’ll generalize this algorihm when we add rules. 16

Rules 17

Rules Rules define new relationships in terms of existing ones parent(X,Y) :- father(X,Y). parent(X,Y) :- mother(X,Y). grandfather(X,Y) :-father(X,Z), parent(Z,Y). Assume facts father(john,mary). mother(mary,jim). Now ask the query ?- grandfather(X,Y). X = john, Y = jim ; false. 18

The Prolog semantics Prolog algorithms in the presence of rules: father(john,mary). mother(mary,jim). grandfather(fim, fum). # 1 parent(X,Y) :- father(X,Y). parent(X,Y) :- mother(X,Y). grandfather(X,Y) :-father(X,Z), parent(Z,Y). # 2 ?- grandfather(X,Y). X = fim, Y = fum ; # matches fact 1 from relation ‘grandfather’ X = john, Y = jim ; # matches head (lhs) of rule 2, which then # creates two new goals from the rhs of 2. false. # lhs = left-hand-side 19

So Prolog can do a simple inference! Joseph Marie Jacquard uses punch cards to instruct a loom to weave "hello, world" into a tapestry. Redditers of the time are not impressed due to the lack of tail call recursion, concurrency, or proper capitalization. … Alain Colmerauer designs the logic language Prolog. His goal is to create a language with the intelligence of a two year old. He proves he has reached his goal by showing a Prolog session that says "No." to every query. 20

Database programming A database programming rule brother(Brother, Sib) :- parent(P, Brother), parent(P, Sib), male(Brother), Brother \= Sib. # same as \=(Brother,Sib) This rule assumes that we have defined relations parent and male. (The \= relation is a built-in.) 21

Database programming In cs164, we will translate SQL-like queries to Prolog. But Prolog can also express richer (recursive) queries: descendant(Y,X) :- parent(X,Y). descendant(Y,X) :- parent(X,Z), descendant(Y,Z). 22

Order of rules and clauses matters 1)Given a goal, Prolog matches facts and rules top- down as they appear in the file. ex: on slide 19, #1 matches before #2 matches. 2)If the rhs of a rule raises multiple goals, they are answered left-to-right. ex: on slide 19, match 2, father(X,Z) is resolved before parent(Z,Y). 23

Test yourself Make sure you understand why these three variants of descendants have different behaviors: v1: descendant(Y,X) :- parent(X,Y). descendant(Y,X) :- parent(X,Z), descendant(Y,Z). v2: descendant(Y,X) :- parent(X,Z), descendant(Y,Z). descendant(Y,X) :- parent(X,Y). v3: descendant(Y,X) :- parent(X,Y). descendant(Y,X) :- descendant(Y,Z), parent(X,Z). 24

Compound terms 25

Compound terms Compound term = functors and arguments. Name of functor is an atom (lower case), not a Var. example: cons(a, cons(b, nil)) A rule: car(Head, List) :- List = cons(Head,Tail). car(Head, cons(Head,Tail)). # equivalent to the above Query: ?- car(Head, cons(a, cons(b, nil)). 26

A simple interpreter A representation of an abstract syntax tree int(3) plus(int(3),int(2)) plus(int(3),minus(int(2),int(3))) An interpreter eval(int(X),X). eval(plus(L,R),Res) :- eval(L,Lv), eval(R, Rv), Res is Lv + Rv. eval(minus(L,R),Res) :- # same as plus 27

Working with lists 28

Lists Lists are just compounds with special, clearer syntax. Cons is denoted with a dot ‘.’.(a,[]) is same as [a|[]]is same as [a].(a,.(b,[]))[a|[b|[[]]][a,b].(a,X)[a|X][a|X] 29

predicate “Am I a list?” Let’s test whether a value is a list list([]). list([X|Xs]) :- list(Xs). Note the common Xs notation for a list of X’s. 30

Let’s define the predicate member Desired usage: ?- member(b, [a,b,c]). true 31

Lists car([X|Y],X). cdr([X|Y],Y). cons(X,R,[X|R]). meaning... –The head (car) of [X|Y] is X. –The tail (cdr) of [X|Y] is Y. –Putting X at the head and Y as the tail constructs (cons) the list [X|R]. From:

An operation on lists: The predicate member/2: member(X,[X|R]). member(X,[Y|R]) :- member(X,R). One can read the clauses the following way: X is a member of a list whose first element is X. X is a member of a list whose tail is R if X is a member of R. 33

List Append append([],List,List). append([H|Tail],X,[H|NewTail]) :- append(Tail,X,NewTail). ?- append([a,b],[c,d],X). X = [a, b, c, d]. ?- append([a,b],X,[a,b,c,d]). X = [c, d]. This is “bidirectional” programming Variables can act as both inputs and outputs 34

More on append ?- append(Y,X,[a,b,c,d]). Y = [], X = [a, b, c, d] ; Y = [a], X = [b, c, d] ; Y = [a, b], X = [c, d] ; Y = [a, b, c], X = [d] ; Y = [a, b, c, d], X = [] ; false. 35

Exercise for you Create an append query with infinitely many answers. ?- append(Y,X,Z). Y = [], X = Z ; Y = [_G613], Z = [_G613|X] ; Y = [_G613, _G619], Z = [_G613, _G619|X] ; Y = [_G613, _G619, _G625], Z = [_G613, _G619, _G625|X] ; 36

Another exercise: desugar AST Want to rewrite each instance of 2*x with x+x: rewrite(times(int(2),R), plus(Rr,Rr)) :- !, rewrite(R,Rr). rewrite(times(L,int(2)), plus(Lr,Lr)) :- !, rewrite(L,Lr). rewrite(times(L,R),times(Lr,Rr)) :- !, rewrite(L,Lr),rewrite(R,Rr). rewrite(int(X),int(X)). 37

And another exercise Analyze a program: 1)Translate a program into facts. 2)Then ask a query which answers whether a program variable is a constant at the of the program. Assume the program contains two statement kinds S ::= S* | def ID = n | if (E) ID = n You can translate the program by hand 38

Some other cool examples to find in tutorials compute the derivative of a function this is example of symbolic manipulation solve a math problem by searching for a solution: “Insert +/- signs between so that the result is 5.” 39

Reading Required download SWI prolog go through a good prolog tutorial, including lists, recursion Recommended The Art of Prolog 40