Prolog - 3 Prolog search trees + traces

Size: px
Start display at page:

Download "Prolog - 3 Prolog search trees + traces"

Transcription

1 Prolog - 3 Prolog search trees + traces 1

2 Review member(a, [A B]). member(a, [B C]) :- member (A,C). goal-oriented semantics: can get value assignment for goal member(a,[b C]) by showing truth of subgoal member(a,c) and retaining value bindings of the variables procedural semantics: think of head of clause as procedure entry, terms as parameters. then body consists of calls within this procedure to do the calculation. variables bindings are like returned values. 2

3 Example?- member(a,[a,b]). yes?- member(a,[b,c]). no?- member(x,[a,b,c]). X = a ; X = b ; X = c ; no Invertability of Prolog arguments 1. member(a, [A B] ). 2. member(a, [B C]) :- member (A, C). 3

4 Example?- member(a,[b, c, X]). X= a ; no?- member(x,y). X = _123 Y = [ X _124] ) ; X = _123 Y = [_125, X _126] ; X = _123 Y = [ _127, _128, X _129] 1. member(a, [A B] ). 2. member(a, [B C]) :- member (A, C). Lazy evaluation of unbounded list structure. An unbound X as first element, second element, third element, etc. 4

5 Prolog Search Tree X=A=a,B=[b,c] member(x,[a,b,c]) X=a success X=A =b,b =[c] X=b success 1. member(a, [A B] ). 2. member(a, [B C]) :- member (A, C). X=A,B=a,C=[b,c] member(x,[b,c]) X=A =c,b =[ ] X=c success X=A,B =b,c =[c] member(x,[c]) X=A B =c, C =[ ] member(a,[ ]) fail fail 5

6 1. member(a, [A B] ). 2. member(a, [B C]) :- member (A, C).?- member(x, [a,b,c]). match rule 1. member(a, [A B] ) so X = A = a, B = [b,c] X = a ; match rule 2. member(a, [B C]) so X = A, B = a, C = [b,c] then evaluate subgoal member(x, [b,c]) match rule 1. member(a,[a B ]) so X = b, B = [c] X = b ; match rule 2. member(a,[b C ]) so X = A, B = b, C = [c] then evaluate subgoal member(x, [c]) match rule 1. member(a,[a B ]) so X=A = c, B =[ ] X = c ; match rule 2. member(a,[b C ]) so X=A, B =c, C =[ ], but member(x, [ ]) is unsatisfiable, no 6

7 Another Search Tree member(a, [b,c,x]) fail, a can t unify with b B = b, C = [c,x] member(a,[c, X]) B =c, C =[X] fail, a can t unify with c 1. member(a, [A B] ). 2. member(a, [B C]) :- member (A, C). X=a, B = [ ] success member(a,[ X]). fail, can t unify [ ] with a list X=B, C = [ ] member(a,[ ]) fail, ditto 7

8 Prolog Search Trees Really have built an evaluation tree for the query member(x,[a,b,c]). Search trees provide a formalism to consider all possible computation paths Leaves are success nodes or failures where computation can proceed no further By convention, to model Prolog, leftmost subgoal is tried first 8

9 Prolog Search Trees, cont. Label edges with variable bindings that occur by unification There can be more than one success node There can be infinite branches in the tree, representing non-terminating computations (performed lazily by Prolog); lazy evaluation implies only generate a node when needed. 9

10 Another Member_of Function Equivalent set of rules: don t care variables mem(a, [A _ ] ). mem(a, [ _ C]) :- mem(a,c). Can examine search tree and see the variables which have been excised were auxiliary variables in the clauses. 10

11 Calculus Example diff(x,1). diff(a,0):-const(a). diff(+(a,b), +(DA,DB)) :- diff(a,da),diff(b,db). diff(sin(a),*(cos(a),da)):- diff(a,da). const(a):-number(a). const(a):-atom(a),\+(a==x). 11

12 Backtracking eat(wolf, lamb). eat(lamb,grass). eat(lion,x):- eat(x,food),plant(food). 12

13 Backtracking eat(wolf, lamb). eat(lamb,grass). eat(lion,x):-eat(x,food),plant(food). plant(grass). Y = X X = wolf, Food = lamb eat(x, Food) eat(lion,y) plant(food) eat(wolf, lamb) fail lamb succeed 13

14 Backtracking eat(wolf, lamb). eat(lamb,grass). eat(lion,x):-eat(x,food),plant(food). plant(grass). Y = X eat(x, Food) X = lamb, Food = grass eat(lion,y) eat(lamb, grass) grass plant(food) succeed succeed 14

15 Tracing in Sicstus Prolog?-[mem]. %loads file mem.pl?-trace. %turns on tracing facility [trace]?- memberof(x,[a,b,c]). (1) 1 Call: memberof(_6783,[a,b,c])? (1) 1 Exit: memberof(a,[a,b,c])? X = a ; (1) 1 Redo: memberof(a,[a,b,c])? (2) 2 Call: memberof(_6783,[b,c])? (2) 2 Exit: memberof(b,[b,c])? (1) 1 Exit: memberof(b,[a,b,c])? X = b ; 1. memberof(a, [A B] ). 2. memberof(a, [B C]) :- memberof (A, C). Matches memberof(a,[a b,c]) with rule #1. Asked for another answer, tries using rule #2. Tries memberof(x,[b,c]) and matches memberof(b,[b c]) with rule #1. 15

16 Tracing in Sicstus Prolog (1) 1 Redo: memberof(b,[a,b,c])? (2) 2 Redo: memberof(b,[b,c])? (3) 3 Call: memberof(_6783,[c])? (3) 3 Exit: memberof(c,[c])? (2) 2 Exit: memberof(c,[b,c])? (1) 1 Exit: memberof(c,[a,b,c])? X = c ; (1) 1 Redo: memberof(c,[a,b,c])? (2) 2 Redo: memberof(c,[b,c])? (3) 3 Redo: memberof(c,[c])? (4) 4 Call: memberof(_6783,[])? (4) 4 Fail: memberof(_6783,[])? (3) 3 Fail: memberof(_6783,[c])? (2) 2 Fail: memberof(_6783,[b,c])? (1) 1 Fail: memberof(_6783,[a,b,c])? no Asked for another answer, tries memberof(x,[b,c]) using rule #2. Tries memberof(x,[c]) and matches memberof(c,[c]) by rule #1. Finds no more choices to try 1. member(a, [A B] ). 2. member(a, [B C]) :- member (A, C). 16

17 Tracing in Prolog call 1.Memberof(A, [A B]). exit success fail 2.Memberof(A,[B C]):- Memberof(A,C) redo 17

18 Still More Append Generating an unbounded number of lists?- append(x,[b],y). X = [ ] Y = [b] ; X = [ _169] Y = [ _169, b] ; X = [ _169, _170 ] Y = [ _169, _170, b] ; etc. 18

19 Generate and Test Paradigm in which Prolog rules generate potential solutions and then test them for the desired properties Used often in simulations with lots of alternatives 19

20 n Queens Problem is given an n by n chessboard, place each of n queens on the board so that no queen can attack another in one move In chess, queens can move either vertically, horizontally or diagonally. This problem is a classic generate and test problem Code on lecture notes webpage 20

21 n Queens not(x):- X,!, fail. %same as saw in class not(_). in(h,[h _]). %same as our member_of in(h,[_ T]):- in(h,t). %%%nums generates a list of integers between two other numbers, L,H by putting the first number at the front of the list returned by a recursive call with a number 1 greater than the first. It only works when the first argument is bound to an integer. It stops when it gets to the higher number. nums(h,h,[h]). nums(l,h,[l R]):- L<H, N is L+1, nums(n,h,r). %%% The number of queens/size of board - use 4 queen_no(4). 21

22 n Queens %%% ranks and files generate the x and y axes of the chess board. Both are lists of numbers up to the number of queens; that is, ranks(l) binds L to the list [1,2,3,,#queens]. ranks(l):- queen_no(n), nums(1,n,l). files(l):- queen_no(n), nums(1,n,l). %%% R is a rank on the board; selects a particular rank R from the list of all ranks L. rank(r):- ranks(l), in(r,l). %%% F is a file on the board; selects a particular file F from the list of all files L. file(f):- files(l), in(f,l). 22

23 n Queens %%% Squares on the board are (rank,file) coordinates. attacks decides if a queen on the square at rank R1, file F1 attacks the square at rank R2, file F2 or vice versa. A queen attacks every square on the same rank, the same file, or the same diagonal. attacks((r,_),(r,_)). attacks((_,f),(_,f)). %a Prolog tuple attacks((r1,f1),(r2,f2)):- diagonal((r1,f1),(r2,f2)). %%%can decompose a Prolog tuple by unification (X,Y)=(1,2) results in X=1,Y=2; tuples have fixed size and there is not head-tail type construct for tuples x same diagonal, diagonal same rank safe placement same file 23

24 n Queens %%% Two squares are on the same diagonal if the slope of the line between them is 1 or -1. Since / is used, real number values for 1 and -1 are needed. diagonal((x,y),(x,y)). %degenerate case, 0 length diag diagonal((x1,y1),(x2,y2)):- N is Y2-Y1,D is X2-X1, Q is N/D, Q is 1.0E+00. %diagonal needs bound args diagonal((x1,y1),(x2,y2)):- N is Y2-Y1, D is X2-X1, Q is N/D, Q is -1.0E+00. %%%because of use of is, diagonal is NOT invertible. 24

25 n Queens %%%placement can be used as a generator. If placement is called with a free variable, it will construct every possible list of squares on the chess board. The first predicate will allow it to establish the empty list as a list of squares on the board. The second predicate will allow it to add any (R,F) pair onto the front of a list of squares if R is a rank of the board and F is a file of the board. placement first generates all 1 element lists, then all 2 element lists, etc. Switching the order of predicates in the second clause will cause it to try varying the length of the list before it varies the squares added to the list placement([]). placement([(r,f) P]):- placement(p), rank(r), file(f). 25

26 n Queens %%%these two routines check the placement of the next queen %%%Checks a list of squares to see that no queen on any of them would attack any other. does by checking that position j doesn t conflict with positions (j+1),(j+2) etc. ok_place([]). ok_place([(r,f) P]):- no_attacks((r,f),p),ok_place(p). %%% Checks that a queen at square (R,F) doesn't attack any square (rank,file pair) in list L; uses attacks predicate defined previously no_attacks(_,[]). no_attacks((r,f),[(r2,f2) P]):- not(attacks((r,f),(r2,f2))), no_attacks((r,f),p). 26

27 n Queens %%% This solution works by generating every list of squares, such that the length of the list is the same as the number of queens, and then checks every list generated to see if it represents a valid placement of queens to solve the N queens problem; assume list length function queens(p):- queen_no(n), length(p,n), placement(p), ok_place(p). generate code given first test code follows 27

28 Unification, Informally Intuitively, unification between 2 Prolog terms tries to assign values to the variables so that the resulting trees, representing the terms, are isomorphic (including matching labels) To use a Prolog rule, we must unify the head of the rule with the subgoal to be proved, matching term by term 28

29 Unification, Informally Given a subgoal <functor>(<term>{, <term>}) how to unify it with a clause head? Rule and subgoal have same name Any uninstantiated variable matches any term If term is also an uninstantiated variable, this means if either takes on a value, they both do Integer and symbolic constants match themselves, only A structured term matches another term iff Has same relation name Has same number of components and corresponding components match 29

30 Unification Unification looks for the most general (or least restrictive) value to assign A substitution (s ) is a finite map from variables to terms in the language append([a B],Y,[A Z]):-...?- append([a,b],[c],w) s: A=a, B=[b], Y=[c], W=[a Z] A term U is an instance of another term T, if there is a substitution s such that U = T s. 30

31 Unification Two terms S,T unify if they have a common instance U (that is, S s 1 = T s 2 = U) Note: if variable X is contained in both S and T, then s 1 and s 2 both must have the same substitution for X. If two terms unify, they can be made identical under some substitution 31

32 Unification There may be more than one substitution to unify two terms times(z,times(y,7)) and times(4,w) s 1 : Z=4, Y=plus(3,5), W=times(plus(3,5),7) s 2 : Z=4, W=times(Y,7) Which substitution is simpler? less restrictive on the values of the variables? s 2 32

33 Most General Unifier We say g is the most general unifier (mgu) of two terms T, W iff for all other unifiers s of T,W, T s is an instance of T g. therefore, s can be obtained by a substitution d applied to g, s = g d?- member(a,b) returns A=_123, B=[A _ ] when it could return A= _123, B=[ A,b] or A=_123, B= [A, c, d] etc. Note, the 2nd and 3rd B values are obtainable from the mgu by additional substitutions 33

Prolog. Intro to Logic Programming

Prolog. Intro to Logic Programming Prolog Logic programming (declarative) Goals and subgoals Prolog Syntax Database example rule order, subgoal order, argument invertibility, backtracking model of execution, negation by failure, variables

More information

Prolog-2 nd Lecture. Prolog Predicate - Box Model

Prolog-2 nd Lecture. Prolog Predicate - Box Model Prolog-2 nd Lecture Tracing in Prolog Procedural interpretation of execution Box model of Prolog predicate rule How to follow a Prolog trace? Trees in Prolog use nested terms Unification Informally Formal

More information

3 Lists. List Operations (I)

3 Lists. List Operations (I) 3 Lists. List Operations (I) The list is the simplest yet the most useful Prolog structure. A list is a sequence of any number of objects. Example 3.1: L = [1, 2, 3], R = [a, b, c], T = [john, marry, tim,

More information

Principles of Programming Languages Topic: Logic Programming Professor Lou Steinberg

Principles of Programming Languages Topic: Logic Programming Professor Lou Steinberg Principles of Programming Languages Topic: Logic Programming Professor Lou Steinberg 1 Logic Programming True facts: If I was born in year B, then in year Y on my birthday I turned Y-B years old I turned

More information

Implementação de Linguagens 2016/2017

Implementação de Linguagens 2016/2017 Implementação de Linguagens Ricardo Rocha DCC-FCUP, Universidade do Porto ricroc @ dcc.fc.up.pt Ricardo Rocha DCC-FCUP 1 Logic Programming Logic programming languages, together with functional programming

More information

Recursion, Structures, and Lists

Recursion, Structures, and Lists Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 4 04/10/04 30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists 1 The central ideas of Prolog

More information

The object level in Prolog. Meta-level predicates and operators. Contents. The flow of computation. The meta level in Prolog

The object level in Prolog. Meta-level predicates and operators. Contents. The flow of computation. The meta level in Prolog Lecture 8 Meta-level predicates and operators Contents Object level vs. meta level Controlling flow of computation Checking and dismantling expressions Comparison operators The object level in Prolog Prolog

More information

Overview. Declarative Languages. operation of del. Deleting an element from a list. functions using del. inserting elements with del

Overview. Declarative Languages. operation of del. Deleting an element from a list. functions using del. inserting elements with del Overview Declarative Languages D7012E: Arithmetic and Backtracking Fredrik Bengtsson Some standard functions Operators Arithmetic The eight queens problem Controlling backtracking cut Deleting an element

More information

Exercises on the Fundamentals of Prolog

Exercises on the Fundamentals of Prolog 1 Introduction Exercises on the Fundamentals of Prolog These exercises are intended to help reinforce material taught in the lectures of CIS335 course in Prolog. They do not contribute any marks to the

More information

n Bottom-up (LR) parsing n Characteristic Finite State Machine (CFSM) n SLR(1) parsing table n Conflicts in SLR(1) n LR parsing variants

n Bottom-up (LR) parsing n Characteristic Finite State Machine (CFSM) n SLR(1) parsing table n Conflicts in SLR(1) n LR parsing variants Aoucemets Gradig HW1 Should be doe by the ed of today. Grades are set to release toight You have 1 week to issue re-grade request Raibow grades comig up over the weeked Last Class Bottom-up (LR) parsig

More information

Prolog. Logic Programming vs Prolog

Prolog. Logic Programming vs Prolog Language constructs Prolog Facts, rules, queries through examples Horn clauses Goal-oriented semantics Procedural semantics How computation is performed? Comparison to logic programming 1 Logic Programming

More information

Tests, Backtracking, and Recursion

Tests, Backtracking, and Recursion Tests, Backtracking, and Recursion Artificial Intelligence Programming in Prolog Lecture 3 30/09/04 30/09/04 AIPP Lecture 3: Rules, Results, and Backtracking 1 Re-cap A Prolog program consists of predicate

More information

10. Logic Programming With Prolog

10. Logic Programming With Prolog Copyright (C) R.A. van Engelen, FSU Department of Computer Science, 2000 10. Logic Programming With Overview Logic Programming Logic Programming Logic programming is a form of declarative programming A

More information

Lecture 6: Recursion RECURSION

Lecture 6: Recursion RECURSION Lecture 6: Recursion RECURSION You are now Java experts! 2 This was almost all the Java that we will teach you in this course Will see a few last things in the remainder of class Now will begin focusing

More information

Prolog (cont d) Remark. Using multiple clauses. Intelligent Systems and HCI D7023E

Prolog (cont d) Remark. Using multiple clauses. Intelligent Systems and HCI D7023E Intelligent Systems and HCI D703E Lecture : More Prolog Paweł Pietrzak Prolog (cont d) 1 Remark The recent version of SWI- Prolog displays true and false rather than and no Using multiple clauses Different

More information

Introduction to Logic Programming. Ambrose

Introduction to Logic Programming. Ambrose Introduction to Logic Programming Ambrose Bonnaire-Sergeant @ambrosebs abonnairesergeant@gmail.com Introduction to Logic Programming Fundamental Logic Programming concepts Related to FP General implementation

More information

Family Example: Some Facts. respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara).

Family Example: Some Facts. respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara). Family Example: Some Facts respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara). Some Queries?- respects(barb,katie). yes?- respects(barb,x). X=dan; % you type ; and RETURN

More information

Connection between Lists and Terms. Prolog-Lecture 2. Unifying Lists. Unifying Lists. Steps to a Recursive Predicate. List Predicates.

Connection between Lists and Terms. Prolog-Lecture 2. Unifying Lists. Unifying Lists. Steps to a Recursive Predicate. List Predicates. Prolog-Lecture 2 Iqbal Mohomed Connection between Lists and Terms [H T] is just syntactic sugaring for the term.(h,t)?-.(h,t) = [a,b,c]. H = a T = [b, c] ; The dot operator or functor. corresponds to cons

More information

Agenda. CS301 Session 20. A logic programming trick. A simple Prolog program. Introduction to logic programming Examples Semantics

Agenda. CS301 Session 20. A logic programming trick. A simple Prolog program. Introduction to logic programming Examples Semantics CS301 Session 20 Introduction to logic programming Examples Semantics Agenda 1 2 A logic programming trick A two-way translator in two lines of code: translate([],[]). translate([word Words],[Mot Mots])

More information

Computational Logic Prolog Programming Basics

Computational Logic Prolog Programming Basics Computational Logic Prolog Programming Basics 1 Overview 1. Using unification 2. Data structures 3. Recursion, backtracking, and search 4. Control of execution 2 Role of Unification in Execution As mentioned

More information

Prolog Programming Basics. Computational Logic. Overview. 3. Recursion, backtracking, and search. 2. Data structures. 1.

Prolog Programming Basics. Computational Logic. Overview. 3. Recursion, backtracking, and search. 2. Data structures. 1. Computational Logic Prolog Programming Basics 1 Overview 1. Using unification 2. Data structures 3. Recursion, backtracking, and search 4. Control of execution 2 Role of Unification in Execution As mentioned

More information

Operational Semantics

Operational Semantics 15-819K: Logic Programming Lecture 4 Operational Semantics Frank Pfenning September 7, 2006 In this lecture we begin in the quest to formally capture the operational semantics in order to prove properties

More information

Prolog Examples. Distributed Systems / Technologies. Sistemi Distribuiti / Tecnologie

Prolog Examples. Distributed Systems / Technologies. Sistemi Distribuiti / Tecnologie Prolog Examples Distributed Systems / Technologies Sistemi Distribuiti / Tecnologie Giovanni Ciatto giovanni.ciatto@unibo.it Andrea Omicini andrea.omicini@unibo.it Dipartimento di Informatica Scienza e

More information

LING/C SC/PSYC 438/538. Lecture 15 Sandiway Fong

LING/C SC/PSYC 438/538. Lecture 15 Sandiway Fong LING/C SC/PSYC 438/538 Lecture 15 Sandiway Fong Did you install SWI Prolog? SWI Prolog Cheatsheet At the prompt?- Everything typed at the 1. halt. prompt must end in a period. 2. listing. listing(name).

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Logic Programming with Prolog Lists CMSC 330 Spring 2017 1 Review: Execution = Search Prolog execution: Goal-directed search Query = predicate you wish to

More information

Chapter 16. Logic Programming Languages

Chapter 16. Logic Programming Languages Chapter 16 Logic Programming Languages Chapter 16 Topics Introduction A Brief Introduction to Predicate Calculus Predicate Calculus and Proving Theorems An Overview of Logic Programming The Origins of

More information

LING/C SC/PSYC 438/538. Lecture 20 Sandiway Fong

LING/C SC/PSYC 438/538. Lecture 20 Sandiway Fong LING/C SC/PSYC 438/538 Lecture 20 Sandiway Fong Today's Topics SWI-Prolog installed? We will start to write grammars today Quick Homework 8 SWI Prolog Cheatsheet At the prompt?- 1. halt. 2. listing. listing(name).

More information

Derived from PROgramming in LOGic (1972) Prolog and LISP - two most popular AI languages. Prolog programs based on predicate logic using Horn clauses

Derived from PROgramming in LOGic (1972) Prolog and LISP - two most popular AI languages. Prolog programs based on predicate logic using Horn clauses Prolog Programming Derived from PROgramming in LOGic (1972) Good at expressing logical relationships between concepts Prolog and LISP - two most popular AI languages Execution of a Prolog program is a

More information

Logic Programming Languages

Logic Programming Languages Logic Programming Languages Introduction Logic programming languages, sometimes called declarative programming languages Express programs in a form of symbolic logic Use a logical inferencing process to

More information

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion simple and/or composition of goals hides complex control patterns not easily represented by traditional

More information

CS 321 Programming Languages and Compilers. Prolog

CS 321 Programming Languages and Compilers. Prolog CS 321 Programming Languages and Compilers Prolog Prolog PROgramming LOGic Algorithm = Logic + Control Logic programming deals with computing relations rather than functions. To understand Prolog one must

More information

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion simple and/or composition of goals hides complex control patterns not easily represented by traditional

More information

Topic B: Backtracking and Lists

Topic B: Backtracking and Lists Topic B: Backtracking and Lists 1 Recommended Exercises and Readings From Programming in Prolog (5 th Ed.) Readings: Chapter 3 2 Searching for the Answer In order for a Prolog program to report the correct

More information

CSC324 Logic & Relational Programming Illustrated in Prolog

CSC324 Logic & Relational Programming Illustrated in Prolog CSC324 Logic & Relational Programming Illustrated in Prolog Afsaneh Fazly 1 Winter 2013 1 with many thanks to Anya Tafliovich, Gerald Penn and Sheila McIlraith. 1 2 admin notes Please check your marks

More information

COMP2411 Lecture 20: Logic Programming Examples. (This material not in the book)

COMP2411 Lecture 20: Logic Programming Examples. (This material not in the book) COMP2411 Lecture 20: Logic Programming Examples (This material not in the book) There are several distinct but often equivalent ways to think about logic programs 1. As computing logical consequences of

More information

Arithmetic Terms are Symbolic

Arithmetic Terms are Symbolic Arithmetic Terms are Symbolic Evaluation of an arithmetic term into a numeric value must be forced. That is, 1+2 is an infix representation of the relation +(1,2). This term is not an integer! Therefore?-

More information

About these slides Prolog programming hints

About these slides Prolog programming hints About these slides Prolog programming hints COMP9414-2008 Semester 1 Ronnie Taib (ronniet@cse.unsw.edu.au)! Practical notes on using Prolog! Some hints for better code! LECTURE NOTES ALWAYS PREVAIL!! The

More information

The current topic: Prolog. Announcements. Meaning of a Prolog rule. Prolog syntax. Reminder: The deadline for Lab 2 re-mark requests is Friday.

The current topic: Prolog. Announcements. Meaning of a Prolog rule. Prolog syntax. Reminder: The deadline for Lab 2 re-mark requests is Friday. The current topic: Prolog! Introduction! Object-oriented programming: Python! Functional programming: Scheme! Python GUI programming (Tkinter)! Types and values Logic programming: Prolog! Introduction

More information

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog CS 360: Programming Languages Lecture 10: Logic Programming with Prolog Geoffrey Mainland Drexel University Section 1 Administrivia Midterm Tuesday Midterm is Tuesday, February 14! Study guide is on the

More information

COP4020 Programming Languages. Logical programming with Prolog Prof. Xin Yuan

COP4020 Programming Languages. Logical programming with Prolog Prof. Xin Yuan COP4020 Programming Languages Logical programming with Prolog Prof. Xin Yuan Topics Logic programming with Prolog COP4020 Spring 2013 2 Definitions: Prolog Terms Terms are symbolic expressions that are

More information

Lecture 21: Relational Programming II. November 15th, 2011

Lecture 21: Relational Programming II. November 15th, 2011 Lecture 21: Relational Programming II November 15th, 2011 Lecture Outline Relational Programming contd The Relational Model of Computation Programming with choice and Solve Search Strategies Relational

More information

A second life for Prolog

A second life for Prolog A second life for Prolog Algorithm = Logic + Control Jan Wielemaker J.Wielemaker@cwi.nl 1 Overview Algorithm = Logic + Control Limitations of SLD Beyond SLD 2 Algorithm = Logic + Control In Logic programming

More information

A Pearl on SAT Solving in Prolog (extended abstract)

A Pearl on SAT Solving in Prolog (extended abstract) A Pearl on SAT Solving in Prolog (extended abstract) Jacob M. Howe and Andy King 1 Introduction The Boolean satisfiability problem, SAT, is of continuing interest because a variety of problems are naturally

More information

proof through refutation

proof through refutation Prolog's logic; resolution grammars & parsing 1 proof through refutation we saw that Prolog uses the strategy: test the claim that a query is false by (1) finding it is immediately true (matches a fact

More information

Chapter 16. Logic Programming Languages ISBN

Chapter 16. Logic Programming Languages ISBN Chapter 16 Logic Programming Languages ISBN 0-321-49362-1 Chapter 16 Topics Introduction A Brief Introduction to Predicate Calculus Predicate Calculus and Proving Theorems An Overview of Logic Programming

More information

Logic Programming. Let us have airline flight information of the form: 1. Application Domains: 2. Definitions

Logic Programming. Let us have airline flight information of the form: 1. Application Domains: 2. Definitions Logic Programming 1. Application Domains: Logic programming language application areas include natural language processing, expert systems, specifications checking, theorem proving, and control systems

More information

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy Topics Chapter 16 Logic Programming Summary (resolution, unification, Prolog search strategy ) Disjoint goals The cut operator Negative goals Predicate fail Debugger / tracer Lists 2 Resolution Resolution

More information

MATH 22 MORE ABOUT FUNCTIONS. Lecture M: 10/14/2003. Form follows function. Louis Henri Sullivan

MATH 22 MORE ABOUT FUNCTIONS. Lecture M: 10/14/2003. Form follows function. Louis Henri Sullivan MATH 22 Lecture M: 10/14/2003 MORE ABOUT FUNCTIONS Form follows function. Louis Henri Sullivan This frightful word, function, was born under other skies than those I have loved. Le Corbusier D ora innanzi

More information

Advanced Prolog Programming

Advanced Prolog Programming 1 Introduction CIS335, Assignment 4 Advanced Prolog Programming Geraint Wiggins November 12, 2004 This practical is the second self-assessed exercise for MSc students on the Prolog module. It is intended

More information

Lecture 4: Backtracking and Cut 1. Lecture 4: Backtracking and Cut. Ahmed Sallam

Lecture 4: Backtracking and Cut 1. Lecture 4: Backtracking and Cut. Ahmed Sallam LOGIC Lecture 4: Backtracking and Cut 1 Lecture 4: Backtracking and Cut Ahmed Sallam Backtracking and Cut Lecture 2 4: Backtracking and Cut Review Backtracking Cut Cut uses Problems with Cut Backtracking

More information

What s the problem? fib(1,1). fib(2,1). fib(n,x) :- N>2, N1 is N-1, N2 is N-2, fib(n1,x2), fib(n2,x2).

What s the problem? fib(1,1). fib(2,1). fib(n,x) :- N>2, N1 is N-1, N2 is N-2, fib(n1,x2), fib(n2,x2). 39 What s the problem? A Fibonacci Implementation fib(1,1). fib(2,1). fib(n,x) :- N>2, N1 is N-1, N2 is N-2, fib(n1,x2), fib(n2,x2). List Concatenation conc([],l,l). conc([x L1], L2, [X L3]) :- conc(l1,l2,l3).

More information

documenting programs, including: A traditional, command line interactive top level.

documenting programs, including: A traditional, command line interactive top level. Computational Logic Developing Programs with a Logic Programming System 1 Our Development Environment: The Ciao System We use the (ISO-Prolog subset of the) Ciao multiparadigm programming system. In particular,

More information

What needs to be kept track of ffl The current substitution ffl The current goal ffl The clause currently in use ffl Backtrack Information 2

What needs to be kept track of ffl The current substitution ffl The current goal ffl The clause currently in use ffl Backtrack Information 2 Prolog Implementation ffl The Generic Idea: Everything except unification. ffl An Introduction to the WAM: Flat unification only. 1 What needs to be kept track of ffl The current substitution ffl The current

More information

Lecture 16: Logic Programming in Prolog

Lecture 16: Logic Programming in Prolog Lecture 16: Logic Programming in Prolog COMP 524 Programming Language Concepts Stephen Olivier March 26, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goal of

More information

Constraint (Logic) Programming

Constraint (Logic) Programming Constraint (Logic) Programming Roman Barták Faculty of Mathematics and Physics, Charles University in Prague, Czech Republic bartak@ktiml.mff.cuni.cz Sudoku Combinatorial puzzle, whose goal is to enter

More information

Computation Club: Gödel s theorem

Computation Club: Gödel s theorem Computation Club: Gödel s theorem The big picture mathematicians do a lot of reasoning and write a lot of proofs formal systems try to capture the ideas of reasoning and proof in a purely mechanical set

More information

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

More information

Programming Languages Prolog Programming Project Due Wednesday, December 5 th, 2001

Programming Languages Prolog Programming Project Due Wednesday, December 5 th, 2001 Programming Languages Prolog Programming Project Due Wednesday, December 5 th, 2001 How Prolog Works Although Prolog is a very powerful and expressive programming environment, it is surprisingly easy to

More information

Combining Lists & Built-in Predicates

Combining Lists & Built-in Predicates Combining Lists & Built-in Predicates Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 6 11/10/04 11/10/04 AIPP Lecture 6: Built-in Predicates 1 Collecting Results Last time we

More information

1 I am given. (Label the triangle with letters and mark congruent parts based on definitions.)

1 I am given. (Label the triangle with letters and mark congruent parts based on definitions.) Name (print first and last) Per Date: 12/13 due 12/15 5.2 Congruence Geometry Regents 2013-2014 Ms. Lomac SLO: I can use SAS to prove the isosceles triangle theorem. (1) Prove: If a triangle is isosceles

More information

Finite Math - J-term Homework. Section Inverse of a Square Matrix

Finite Math - J-term Homework. Section Inverse of a Square Matrix Section.5-77, 78, 79, 80 Finite Math - J-term 017 Lecture Notes - 1/19/017 Homework Section.6-9, 1, 1, 15, 17, 18, 1, 6, 9, 3, 37, 39, 1,, 5, 6, 55 Section 5.1-9, 11, 1, 13, 1, 17, 9, 30 Section.5 - Inverse

More information

Lecture 9: A closer look at terms

Lecture 9: A closer look at terms Lecture 9: A closer look at terms Theory Introduce the == predicate Take a closer look at term structure Introduce strings in Prolog Introduce operators Exercises Exercises of LPN: 9.1, 9.2, 9.3, 9.4,

More information

The tupinjade package

The tupinjade package The tupinjade package The tupinjade package defines the following classes: ErrorMsg: this class is used by the tuprolog agents running in a JADE platform with the aim of displaying a pop-up window with

More information

Artificial Intelligence. Chapters Reviews. Readings: Chapters 3-8 of Russell & Norvig.

Artificial Intelligence. Chapters Reviews. Readings: Chapters 3-8 of Russell & Norvig. Artificial Intelligence Chapters Reviews Readings: Chapters 3-8 of Russell & Norvig. Topics covered in the midterm Solving problems by searching (Chap. 3) How to formulate a search problem? How to measure

More information

Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Functional & Logic Programming - Backtracking October, 01

Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Functional & Logic Programming - Backtracking October, 01 Functional & Logic Programming - October, 01 already seen how to control execution ordering the clauses and goals can affect the speed of execution and the order of evaluation of the clauses now going

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Context Free Grammars and Parsing 1 Recall: Architecture of Compilers, Interpreters Source Parser Static Analyzer Intermediate Representation Front End Back

More information

Introduction (1A) Young Won Lim 9/12/13

Introduction (1A) Young Won Lim 9/12/13 Introduction (1A) Copyright (c) 2013 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

Introduction. CSc 372. Comparative Programming Languages. 22 : Prolog Lists. Department of Computer Science University of Arizona.

Introduction. CSc 372. Comparative Programming Languages. 22 : Prolog Lists. Department of Computer Science University of Arizona. CSc 372 Comparative Programming Languages 22 : Prolog Lists Introduction Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg Christian Collberg Prolog

More information

Fundamentals of Prolog

Fundamentals of Prolog Fundamentals of Prolog Prof. Geraint A. Wiggins Centre for Cognition, Computation and Culture Goldsmiths College, University of London Contents Summary of Lecture 1 What makes a good Prolog program? What

More information

INTRODUCTION TO PROLOG

INTRODUCTION TO PROLOG INTRODUCTION TO PROLOG PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/44 STRUCTURE OF A PROLOG PROGRAM Where, declaratively, Haskell expresses a computation as a system

More information

PM - A REDUCE Pattern Matcher

PM - A REDUCE Pattern Matcher PM - A REDUCE Pattern Matcher Kevin McIsaac The University of Western Australia and The RAND Corporation kevin@wri.com PM is a general pattern matcher similar in style to those found in systems such as

More information

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference Lecture #13: Type Inference and Unification Typing In the Language ML Examples from the language ML: fun map f [] = [] map f (a :: y) = (f a) :: (map f y) fun reduce f init [] = init reduce f init (a ::

More information

Logic Languages. Hwansoo Han

Logic Languages. Hwansoo Han Logic Languages Hwansoo Han Logic Programming Based on first-order predicate calculus Operators Conjunction, disjunction, negation, implication Universal and existential quantifiers E A x for all x...

More information

Prolog lecture 5. Data structures Difference lists Appendless append

Prolog lecture 5. Data structures Difference lists Appendless append Prolog lecture 5 Data structures Difference lists Appendless append Appending two Lists Predicate definition is elegantly simple: append([],l,l). append([x T],L,[X R]) :- append(t,l,r). Run-time performance

More information

Part I Logic programming paradigm

Part I Logic programming paradigm Part I Logic programming paradigm 1 Logic programming and pure Prolog 1.1 Introduction 3 1.2 Syntax 4 1.3 The meaning of a program 7 1.4 Computing with equations 9 1.5 Prolog: the first steps 15 1.6 Two

More information

SAT solver of Howe & King as a logic program

SAT solver of Howe & King as a logic program SAT solver of Howe & King as a logic program W lodzimierz Drabent June 6, 2011 Howe and King [HK11b, HK11a] presented a SAT solver which is an elegant and concise Prolog program of 22 lines. It is not

More information

Prolog Programming. Lecture Module 8

Prolog Programming. Lecture Module 8 Prolog Programming Lecture Module 8 Prolog Language Prolog is unique in its ability to infer facts from the given facts and rules. In Prolog, an order of clauses in the program and goals in the body of

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Logic Programming Language Paradigm Topics Introduction A Brief Introduction to Predicate Calculus Predicate Calculus and Proving Theorems An Overview of Logic

More information

Processing lists in Prolog - 2

Processing lists in Prolog - 2 Processing lists in Prolog - 2 This lecture shows that techniques introduced before (analysing terminating conditions and recursive programming) can be used to develop more complex procedures. This lecture

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

Fall Lecture 13 Thursday, October 11

Fall Lecture 13 Thursday, October 11 15-150 Fall 2018 Lecture 13 Thursday, October 11 n queens One s favorite ipod app n queens Queens attack on row, column, or diagonal Task: put n queens safely on an n-by-n board British Museum algorithm

More information

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming The Idea Underlying CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Department of Computer Science and Engineering University of Minnesota Lectures in Fall

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

Logic Programming in Prolog

Logic Programming in Prolog Cristian Giumale / Lecture Notes 1 Logic Programming in Prolog There are important advantages of using programming systems based on logic: Data are neatly separated from the inference engine, which is

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 11 Functional Programming with Haskell 1/37 Programming Paradigms Unit 11 Functional Programming with Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

LOGIC PROGRAMMING. Ahmed Sallam. Lecture 4: Backtracking and Cut. Lecture 4: Backtracking and Cut 1

LOGIC PROGRAMMING. Ahmed Sallam. Lecture 4: Backtracking and Cut. Lecture 4: Backtracking and Cut 1 LOGIC PROGRAMMING 1 Ahmed Sallam Backtracking and Cut 2 Review Backtracking Cut Cut uses Problems with Cut Backtracking 3 Backtracking and Cut 4 Review Backtracking Cut Cut uses Problems with Cut The "Cut

More information

Notes. Notes. Introduction. Notes. Propositional Functions. Slides by Christopher M. Bourke Instructor: Berthe Y. Choueiry.

Notes. Notes. Introduction. Notes. Propositional Functions. Slides by Christopher M. Bourke Instructor: Berthe Y. Choueiry. Slides by Christopher M. Bourke Instructor: Berthe Y. Choueiry Spring 2006 1 / 1 Computer Science & Engineering 235 Introduction to Discrete Mathematics Sections 1.3 1.4 of Rosen cse235@cse.unl.edu Introduction

More information

Conjunctive queries. Many computational problems are much easier for conjunctive queries than for general first-order queries.

Conjunctive queries. Many computational problems are much easier for conjunctive queries than for general first-order queries. Conjunctive queries Relational calculus queries without negation and disjunction. Conjunctive queries have a normal form: ( y 1 ) ( y n )(p 1 (x 1,..., x m, y 1,..., y n ) p k (x 1,..., x m, y 1,..., y

More information

Automatic Reasoning (Section 8.3)

Automatic Reasoning (Section 8.3) Automatic Reasoning (Section 8.3) Automatic Reasoning Can reasoning be automated? Yes, for some logics, including first-order logic. We could try to automate natural deduction, but there are many proof

More information

Research Report AI A Numerical Equation Solver in Prolog Michael A. Covington Artificial Intelligence Programs The University of Georgia

Research Report AI A Numerical Equation Solver in Prolog Michael A. Covington Artificial Intelligence Programs The University of Georgia Research Report AI 1989 02 A Numerical Equation Solver in Prolog Michael A. Covington Artificial Intelligence Programs The University of Georgia Athens, Georgia 30602 U.S.A. A Numerical Equation Solver

More information

Module 7. Knowledge Representation and Logic (Rule based Systems) Version 2 CSE IIT, Kharagpur

Module 7. Knowledge Representation and Logic (Rule based Systems) Version 2 CSE IIT, Kharagpur Module 7 Knowledge Representation and Logic (Rule based Systems) Lesson 18 Rule based Systems - II 7.2.5 Programs in PROLOG These minimal notes on Prolog show only some of its flavor. Here are facts plays(ann,fido).

More information

Integrity Constraints (Chapter 7.3) Overview. Bottom-Up. Top-Down. Integrity Constraint. Disjunctive & Negative Knowledge. Proof by Refutation

Integrity Constraints (Chapter 7.3) Overview. Bottom-Up. Top-Down. Integrity Constraint. Disjunctive & Negative Knowledge. Proof by Refutation CSE560 Class 10: 1 c P. Heeman, 2010 Integrity Constraints Overview Disjunctive & Negative Knowledge Resolution Rule Bottom-Up Proof by Refutation Top-Down CSE560 Class 10: 2 c P. Heeman, 2010 Integrity

More information

Brief Introduction to Prolog

Brief Introduction to Prolog CSC384: Intro to Artificial Intelligence Brief Introduction to Prolog Prolog Programming for Artificial Intelligence by Ivan Bratko. Prolog is a language that is useful for doing symbolic and logic based

More information

Logic Programming and Resolution Lecture notes for INF3170/4171

Logic Programming and Resolution Lecture notes for INF3170/4171 Logic Programming and Resolution Lecture notes for INF3170/4171 Leif Harald Karlsen Autumn 2015 1 Introduction This note will explain the connection between logic and computer programming using Horn Clauses

More information

Where We Are. CMSC 330: Organization of Programming Languages. This Lecture. Programming Languages. Motivation for Grammars

Where We Are. CMSC 330: Organization of Programming Languages. This Lecture. Programming Languages. Motivation for Grammars CMSC 330: Organization of Programming Languages Context Free Grammars Where We Are Programming languages Ruby OCaml Implementing programming languages Scanner Uses regular expressions Finite automata Parser

More information

Prolog. ATutorialIntroduction. James Lu Jerud J. Mead. Computer Science Department Bucknell University Lewisburg, PA 17387

Prolog. ATutorialIntroduction. James Lu Jerud J. Mead. Computer Science Department Bucknell University Lewisburg, PA 17387 Prolog ATutorialIntroduction James Lu Jerud J. Mead Computer Science Department Bucknell University Lewisburg, PA 17387 1 Contents 1 Introduction 1 2 Easing into Prolog 2 2.1 Logic Programming.........................................

More information

CMSC 330: Organization of Programming Languages. Architecture of Compilers, Interpreters

CMSC 330: Organization of Programming Languages. Architecture of Compilers, Interpreters : Organization of Programming Languages Context Free Grammars 1 Architecture of Compilers, Interpreters Source Scanner Parser Static Analyzer Intermediate Representation Front End Back End Compiler / Interpreter

More information

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Christian Collberg collberg+372@gmail.com Department of Computer Science University of Arizona Copyright c 2005 Christian Collberg

More information

Logic, Programming and Prolog (Supplement)

Logic, Programming and Prolog (Supplement) Logic, Programming and Prolog (Supplement) Ulf Nilsson Dept of Computer and Information Science Linköping University ulfni@ida.liu.se http://www.ida.liu.se/labs/logpro/ulfni c Ulf Nilsson, November 26,

More information

A Third Look At Prolog. Chapter Twenty-Two Modern Programming Languages, 2nd ed. 1

A Third Look At Prolog. Chapter Twenty-Two Modern Programming Languages, 2nd ed. 1 A Third Look At Prolog Chapter Twenty-Two Modern Programming Languages, 2nd ed. 1 Outline Numeric computation in Prolog Problem space search Knapsack 8-queens Farewell to Prolog Chapter Twenty-Two Modern

More information