Lists in Prolog Sections 3.1, 3.2. Testing a List n Suppose have defined female/1 and male/1 n Check whether a list is all male % all_male(?L) % -- male(X)

Slides:



Advertisements
Similar presentations
Artificial Intelligence: Natural Language and Prolog
Advertisements

Formal Models of Computation Part II The Logic Model
CS4026 Formal Models of Computation Part II The Logic Model Lecture 6 – Arithmetic, fail and the cut.
Higher-Order Functions and Loops c. Kathi Fisler,
Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
1 Part 1 The Prolog Language Chapter 2 Syntax and Meaning of Prolog programs.
Prolog.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 6: More Lists Theory –Define append/3, a predicate for concatenating two lists, and illustrate.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/5.
11/10/04 AIPP Lecture 6: Built-in Predicates1 Combining Lists & Built-in Predicates Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture.
Prolog: List © Patrick Blackburn, Johan Bos & Kristina Striegnitz.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/8.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
Situation Calculus for Action Descriptions We talked about STRIPS representations for actions. Another common representation is called the Situation Calculus.
1 Programming Languages and Paradigms Lisp Programming.
Types of Algorithms.
Simply Logical – Chapter 3© Peter Flach, 2000 Luc De Raedt and Andreas Karwath (original slides by Peter Flach) Fortgeschrittene Programmierung PROLOG.
2. Syntax and Meaning. Contents Data Objects Matching Declarative meaning of Prolog Procedural meaning Example: monkey and banana Order of clauses and.
Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
CS 330 Programming Languages 12 / 02 / 2008 Instructor: Michael Eckmann.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
CMPS1371 Introduction to Computing for Engineers SORTING.
Midterm Logistics Where? 2050 VLSB When? Monday, 4:10 to 5:40 What to do? –“Review problems” from Thursday/Friday in UCWise. –Two practice exams and solutions.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Syntax and Meaning of Prolog Programs Notes for Ch.2 of Bratko For CSCE 580.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Using Structures: Example Programs Notes for Ch.4 of Bratko For CSCE 580 Sp03.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Spelling Lists.
Spelling Lists. Unit 1 Spelling List write family there yet would draw become grow try really ago almost always course less than words study then learned.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
1 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus and Robert Moyer, Montgomery County Community.
B-Trees. CSM B-Trees 2 Motivation for B-Trees So far we have assumed that we can store an entire data structure in main memory What if we have so.
14/10/04 AIPP Lecture 7: The Cut1 Controlling Backtracking: The Cut Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 7 14/10/04.
Flow of Control Chapter 5. Flow of Control n What order computer uses to get answers –sub-goal ordering –clause ordering n Prolog flow-of-control –sequence.
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
Prolog Programming. 2 DATA STRUCTURES IN PROLOG PROGRAMMING TECHNIQUES CONTROL IN PROLOG CUTS.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
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.
1 Knowledge Based Systems (CM0377) Lecture 3 (Last modified 5th February 2001)
B-Trees. Motivation for B-Trees So far we have assumed that we can store an entire data structure in main memory What if we have so much data that it.
Function Design in LISP. Program Files n LISP programs are plain text –DOS extensions vary; use.lsp for this course n (load “filename.lsp”) n Can use.
1 More About Turing Machines “Programming Tricks” Restrictions Extensions Closure Properties.
Review: computing list results Many programs require list results to be computed, built and returned Many programs require list results to be computed,
Types of Algorithms. 2 Algorithm classification Algorithms that use a similar problem-solving approach can be grouped together We’ll talk about a classification.
1 CHƯƠNG 4 Creating Relational Databases Understanding Table Relationships Example: This database tracks customers and their orders in two separate.
Negation Chapter 5. Stating Negative Conditions n Sometimes you want to say that some condition does not hold n Prolog allows this –not/1this is a predicate.
Lists in Prolog Sections 3.1, 3.2. Lists n List = sequence of values –[1, 2, 3, 4, 5] –[bob, brian, cathy, mark, david, loretta] –[birds(4, calling),
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
Programming Language Concepts Lecture 17 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Logic Programming.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
For Monday Exam 1 is Monday Takehome due Prolog Handout 3 due.
For Friday No reading Prolog Handout 2. Homework.
Prolog 3 Tests and Backtracking 1. Arithmetic Operators Operators for arithmetic and value comparisons are built-in to Prolog = always accessible / don’t.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
Tests, Backtracking, and Recursion
Types of Algorithms.
Chapter 11 :: Logic Languages
Types of Algorithms.
Chapter 12 :: Logic Languages
Programming Paradigms and Languages
Types of Algorithms.
B-Trees.
Lisp.
Chapter 12 :: Logic Languages
Presentation transcript:

Lists in Prolog Sections 3.1, 3.2

Testing a List n Suppose have defined female/1 and male/1 n Check whether a list is all male % all_male(?L) % -- male(X) for each element X of L n Identify the predicate & its argument(s) –we’ll talk about the ? soon n State the relationship/property that holds

Logic of List Testing n Every element is male n Going to use recursion (no loops!) n Base case –??? n Recursive case –??? What’s the simplest list of all males? No, there’s one simpler than that! What to do if it’s NOT the simplest case?

All Males % all_male(?L) %-- male(X) for all elements X of L all_male([]). all_male([H | T]) :- male(H),all_male(T).

General List Use n Common to want to do stuff with every element of a list –test it, make a copy of it, … n Multi-clause predicate (usually 2) –first clause is base case (usually 0 or 1 element) –last clause recursive case (extracts head, recurs on tail) –extra cases as required

On ?, + and – n Documented argument with ? in front of it –means that arg. can be variable or value n Alternatives are + –should have a value –unbound variables not allowed/bad idea n And – –should not have a value –unbound variables only “bound” = has a value other than just another variable Used in system documentation see help(member), help(is)

Exercise n Write a predicate that takes a fully filled in list of numbers and creates (or tests) a second list where each element is 1 more than in the first list –one_more([1,2,3], L) makes L=[2,3,4] –one_more([1,2,4], [2,3,5]) succeeds –one_more([1,2,5], [2,3,7]) fails n Document it

Case Analysis n Simplest list is the empty list n If the first list is empty, what should the second list be? n If the first list is not empty, how is the head of the second list related to the head of the first? n How are the tails related?

Documentation n How is the second list related to the first? n What notations on the arguments? –?? –+? ––? n What shall we call the arguments?

Possible Solution % one_more(+Less, ?More) %-- N is M+1 for each N in More % and the corresponding M in Less one_more([], []). one_more([M | Ms], [N | Ns]) :- N is M + 1, one_more(Ms, Ns).

Logical Addition %one_more_1(?Less, ?More) % -- N is M+1 for each N in More % and the corresponding M in Less % -- Note: N or M must be instantiated one_more_1([], []). one_more_1([M | Ms], [N | Ns]) :- plus(M, 1, N), one_more(Ms, Ns). % M + 1 is equal to N

Miscellaneous Math Stuff n Logical addition (will fill in any one variable) –plus(X, Y, Z) X + Y is equal to Z –succ(M, N) M + 1 is equal to N n Comparisons (variables bound to expressions) –M P M P –M = = P M  N & N  P –N =:= PN = P –N =\= PN  P

Exercise n Write a predicate all_leq/2 –each element of the first list is less than or equal to the corresponding element of the second –(also, lists are the same length) ?- all_leq([1, 2, 3, 4], [1, 2, 3, 5]). Yes ?- all_leq([1, 2, 3, 4, 5], [7, 6, 5, 4, 3]). No

By Cases in Prolog n Suppose we want to write larger/3 –3 rd argument is larger of 1 st two n Two cases: –first argument is larger than second –first argument is less than or equal to second % larger(+First, +Second, ?Larger) larger(First, Second, First) :- First > Second. larger(First, Second, Second) :- First =< Second.

Splitting a List n Suppose we want to split a list by size: ?- split_by_size(10, [3, 56, 18, 7, 8, 10, 4], L, G). L = [3, 7, 8, 10, 4] G = [56, 18] n 3 rd is elements of 2 nd less than or equal to 1 st n 4 th is elements of 2 nd greater than 1 st n How do we do that?

Specifying the Splitting n Each element of 2 nd in either 3 rd or 4 th split_by_size(N, [H | T2], [H | T3], T4) or split_by_size(N, [H | T2], T3, [H | T4]) –retains the order of elements –not necessary, but not ruled out (document it) n In 2 nd if H  N, in 3 rd if H > N –in either case, split_by_size(N, T2, T3, T4)

Recursive Cases split_by_size(N, [H | T2], [H | T3], T4) :- H =< N, split_by_size(N, T2, T3, T4). split_by_size(N, [H | T2], T3, [H | T4]) :- H > N, split_by_size(N, T2, T3, T4).

Base Case n Before the recursive cases n 2 nd argument = empty list –thus 3 rd argument = empty list –and 4 th argument = empty list split_by_size(_N, [], [], []).

Documentation n N compared to H –so both must be known n N not bound to any other value –must be given (+N) n H bound to first element of two lists –one or the other must be given (?L1, ?L2, ?L3) –note normal usage (split or join or test join)

Split By Size Documentation % split_by_size(+N, ?L, ?S, ?B) %normal use (+N,+L,-S,-B) or (+N,?L,+S,+B) %elts. of S are elts. of L less than/equal to N %elts. of B are elts. of L greater than N %elements in S and B in same order as in L %sample call: %?- split_by_size(10, [3, 21, 10, 12], S, B). %S = [3, 10] %B = [21, 12](no other solutions)

Getting Elements by Position n last/2 queries last element of a list n nth1/3 queries nth element of a list –starts counting at 1 n nth0/3 queries nth element of a list –starts counting at 0

Examples ?- last(L, [a, x, e]). L = e ?- nth0(2, [a, x, e], Elt). Elt = e ?- nth1(N, [a, x, e], e). N = 3 ?- last(_Last, [a, x, e]), nth0(1, [a, x, e], _Second), nth1(2, L, _Second), nth1(1, L, _Last). L = [e, x | _G1]

Insertion and Deletion n Insertion to & deletion from lists –just opposites –three way relationship –shorter list, extra element, longer list –use same predicate for both –select/3 in SWI-Prolog ?- select(ListWithX, X, ListWithoutX).

Using select/3 n To delete an element ?- select([g, o, n, e], n, L). L = [g, o, e] n To insert an element ?- select(L, n, [g, o, e]). L = [n, g, o, e] ; L = [g, n, o, e] ; L = [g, o, n, e] ;

Using select/3 n Deleting any element ?- select([a, b, c], X, Rest). X = a, Rest = [b, c] ; X = b, Rest = [a, c] ; X = c, Rest = [a, b] ; No

Variable Naming Suggestion n Make names like pictures –X removed from LiXst leaves List n Good for append insert(X, List, LiXst) :- select(LiXst, X, List). delete(X, LiXst, List) :- select(LiXst, X, List). double_double(X, RXXSXXT) :- append(R, [X,X|SXXT], RXXSXXT), append(S, [X,X|T], SXXT).

Exercise n Use select/3 to write one_moved/2, a predicate that says that its two (list) arguments are different by only one element being moved. For example: ?- one_moved([t,r,a,i,l], [t,r,i,a,l]). Yes ?- one_moved([f,r,e,e,d], [f,r,e,d]). No

Start, Moves, Goal n Many problems can be formulated as getting from a start state to a goal state thru a sequence of moves –monkey program (section 2.5) –travel program (section 4.4) –NDFAs (section 4.3)

Follow That Monkey n Monkey example (section 2.5) n States – four questions –which part of the room is the monkey in? –is the monkey on the box or on the floor? –where is the box? –does the monkey have the banana? n Actions – grasp, climb, push, walk –last two go from place to place

The Room (Initial State) doorbox window banana monkey atwindowmiddleatdoor

Start and Goal States n Start state: –monkey is at the door (atdoor) –monkey is on the floor (onfloor) –box is at the window (atwindow) –monkey does not have the banana (hasnot) n Goal state: –monkey has the banana (has) –(don’t care about the others)

Monkey Grasps n if the monkey is on the box in the middle of the room, then grasping gets him the banana move(state(middle, onbox, middle, hasnot), grasp, state(middle, onbox, middle, has)). (box must also be in the middle; monkey can’t already have the banana; nothing else changes)

Monkey Climbs n if the monkey is on the floor next to the box, then climbing gets him on the box move(state(Where, onfloor, Where, Has), climb, state(Where, onbox, Where, Has)). (monkey & box stay in the same place; doesn’t change whether the monkey has the banana or not)

Monkey Pushes the Box n if the monkey is on the floor next to the box, then pushing gets both to a new place move(state(OldLoc, onfloor, OldLoc, Has), push(OldLoc, NewLoc), state(NewLoc, onfloor, NewLoc, Has)). (monkey & box both move to new place; monkey stays on floor; doesn’t change whether the monkey has the banana or not)

Monkey Walks Somewhere n if the monkey is on the floor, walking gets him to a new position move(state(OldLoc, onfloor, Where, Has), walk(OldLoc, NewLoc), state(NewLoc, onfloor, Where, Has)). (monkey stays on floor; box doesn’t move; doesn’t change whether the monkey has the banana or not)

To Get the Banana n canget/1 gets the monkey to the banana –query = initial state –base case = goal state –recursive case: make any move & try again n Shows monkey can get the banana… n …but doesn’t say how n Add a list to canget/1 to make canget/2 –list shows the moves the monkey makes

canget/2 % canget(+State, ?Moves) %monkey can get banana from State by Moves % nothing to do if monkey has banana canget(state(_,_,_,has), []). % else make a move & continue canget(S1, [Move | Moves]) :- move(S1, Move, S2), canget(S2, Moves). List is built as moves get made Will change if backtracking occurs

How to Get the Banana ?- canget(state(atdoor, onfloor, atwindow, hasnot), Moves). (doesn’t have it yet) (can’t grasp it) (can’t climb box) (can’t push box) (walk somewhere (NewLoc)) state(NewLoc, onfloor, atwindow, hasnot)

How to Get the Banana canget(state(NewLoc, onfloor, atwindow, hasnot), Moves). (doesn’t have it yet) (can’t grasp it) (climb box (if he walked to the window)) state(atwindow, onbox, atwindow, hasnot)

How to Get the Banana canget(state(atwindow, onbox, atwindow, hasnot), Moves). (doesn’t have it yet) (can’t grasp it) (can’t climb box) (can’t push box) (can’t walk anywhere) (dead end – back up to walking somewhere)

How to Get the Banana canget(state(NewLoc, onfloor, atwindow, hasnot), Moves). (didn’t have it yet) (couldn’t grasp it) (climbing box didn’t work) (push box somwhere (if he walked to the window)) state(NewLoc, onfloor, NewLoc, hasnot)

How to Get the Banana canget(state(NewLoc, onfloor, NewLoc, hasnot), Moves). (doesn’t have it yet) (can’t grasp it) (climb box) state(NewLoc, onbox, NewLoc, hasnot)

How to Get the Banana canget(state(NewLoc, onbox, NewLoc, hasnot), Moves). (doesn’t have it yet) (grasp it – if he pushed the box to the middle) state(middle, onbox, middle, has)

How to Get the Banana canget(state(middle, onbox, middle, has), Moves). (has it – nothing left to do)

How to Get the Banana ?- canget(state(atdoor, onfloor, atwindow, hasnot), Moves). Moves = [walk(atdoor, atwindow), push(atwindow, middle), climb,grasp]

NDFAs n Simulating NDFAs works same way –list of symbols gets us from start to end n May have multiple goal states –represented by final/1 n Usually give list & see if it gets us to a goal –instead of giving initial state & finding list to get us to goal

NDFA Moves n Like monkey moves, but simpler trans(s1, a, s1). –getting/doing a in state s1 moves you to state s1 –cf. move(OldState, Move, NewState). n “Silent” moves can just happen silent(s2, s4). –doing nothing in s2 can move you to s4

NDFA Acceptance n Just like getting list of moves for monkey accept(State, []) :- final(State). (like canget(state(_,_,_,has), [])) accept(State, [Move|Moves]) :- trans(State, Move, NewState), accept(NewState, Moves). (like canget(FromState, ByMoves) rule)

Planning for a Trip n At a given place, need to be somewhere else n Have certain moves available n Want a list of moves to make n Just like the monkey n General goal search method applies –some specialization may help

Trip Predicates n canreach(FromCity, ToCity, Flights) –like canget/accept n flight(Number, From, To, Dep, Arr) –like move/trans ?- canreach(halifax, detroit, Flights). Flights = [fly(ac1023, halifax, toronto, 10:00, 12:05), fly(nw235, toronto, detroit, 14:30, 15:45)]

canreach/3 canreach(City, City, []). canreach(From, To, [fly(N,From,Stop,D,A)|Flights]) :- flight(N, From, Stop, D, A), canreach(Stop, To, Flights). flight(ac1023, halifax, toronto, 10:00, 12:05). flight(nw235, toronto, detroit, 14:30, 15:45). flight(ac1035, halifax, moncton, 11:30, 12:15).

More Elaborate Planning n Travel planning (section 4.4) –not all flights go every day –whole trip on one day –allow 40 minutes for transfers n Otherwise just a lot of fluff –P1-P3 : Fnum : Deptime is same as fly(Fnum, P1, P3, Deptime, _)

Listing Flights n Flight database, p. 101 (p. 112, 2 nd e) –timetable/3 would be better as flight/6 flight(edinburgh, london, ba4733, 9:40, 10:50, alldays). n Get cities just as fast n Don’t have to break up structures to get at data –structures should be used to lump info together –each lump can be used as a unit (see family, 4.1,2)

Next Time n Controlling backtracking –Chapter 5