Lists in Prolog Sections 3.1, 3.2. Lists n List = sequence of values –[1, 2, 3, 4, 5] –[bob,...

53
Lists in Prolog Lists in Prolog Sections 3.1, 3.2 Sections 3.1, 3.2

Transcript of Lists in Prolog Sections 3.1, 3.2. Lists n List = sequence of values –[1, 2, 3, 4, 5] –[bob,...

Page 1: 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),

Lists in PrologLists in Prolog

Sections 3.1, 3.2Sections 3.1, 3.2

Page 2: 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),

ListsLists

List = sequence of valuesList = sequence of values– [1, 2, 3, 4, 5][1, 2, 3, 4, 5]– [bob, brian, cathy, mark, david, loretta][bob, brian, cathy, mark, david, loretta]– [birds(4, calling), hens(3, french), doves(2, turtle), [birds(4, calling), hens(3, french), doves(2, turtle),

partridge(1, in(tree(1,pear)))]partridge(1, in(tree(1,pear)))]– [X, Y, Z, Z, Y][X, Y, Z, Z, Y]– [1, brian, doves(2, turtle), Z][1, brian, doves(2, turtle), Z]

Page 3: 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),

Representations of ListsRepresentations of Lists

Written in [square] bracketsWritten in [square] brackets– Note: (parentheses), [brackets], {braces}Note: (parentheses), [brackets], {braces}– mean different things in computer languagesmean different things in computer languages

Elements, separated, by, commasElements, separated, by, commas Each element can be Each element can be anythinganything

– atom, term, variable, or listatom, term, variable, or list Simplest list is the empty list: []Simplest list is the empty list: []

Page 4: 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),

Head and TailHead and Tail

First element of a list is called its First element of a list is called its headhead Everything else in list is part of the Everything else in list is part of the tailtail

– tail AKA “the rest of the list”tail AKA “the rest of the list”– tail is tail is itselfitself a list a list

[1, b, 3, 5][1, b, 3, 5]– head is 1 – note: an atom (head is 1 – note: an atom (in this examplein this example))– tail is [b, 3, 5] – note: a list (tail is [b, 3, 5] – note: a list (alwaysalways))

Page 5: 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),

List DecapitationList Decapitation

Can separate the head from the tailCan separate the head from the tail [Head | Tail][Head | Tail]

– use upright bar instead of commause upright bar instead of comma

?- ?- [1, b, 3, 5] = [Head | Tail].[1, b, 3, 5] = [Head | Tail].

Head = 1Head = 1

Tail = [b, 3, 5]Tail = [b, 3, 5]

YesYes

Page 6: 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),

List DeconstructionList Deconstruction

Can actually pull any number of elements Can actually pull any number of elements off the front of the listoff the front of the list

?- ?- [1, 2, 3, 4, 5, 6] = [A, B, C | Tail].[1, 2, 3, 4, 5, 6] = [A, B, C | Tail].

A = 1A = 1

B = 2B = 2

C = 3C = 3

Tail = [4, 5, 6]Tail = [4, 5, 6]

No comma in front of the bar

Page 7: 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),

Deconstruct Only At FrontDeconstruct Only At Front

Can’t get at the back elements (directly)Can’t get at the back elements (directly)

?- ?- [1, 2, 3, 4, 5] = [Head | Tail, Last].[1, 2, 3, 4, 5] = [Head | Tail, Last].

NoNo Only one item appears after the barOnly one item appears after the bar

– it will become a list, if it isn’t alreadyit will become a list, if it isn’t already

Page 8: 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),

Empty TailsEmpty Tails

It’s OK if the tail is the empty listIt’s OK if the tail is the empty list

?- ?- [Head | Tail] = [alone].[Head | Tail] = [alone].Head = alone, Tail = []Head = alone, Tail = []?- ?- [A, B | Rest] = [1, 2].[A, B | Rest] = [1, 2].A = 1, B = 2, Rest = []A = 1, B = 2, Rest = []?- ?- [A, B, C | More] = [1, 2].[A, B, C | More] = [1, 2].NoNo

Page 9: 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),

Constructing ListsConstructing Lists

Same way as you Same way as you dedeconstruct themconstruct them– only in reverseonly in reverse

?- ?- _H = 1, _T = [2, 3, 4], L = [_H | _T]._H = 1, _T = [2, 3, 4], L = [_H | _T].

L = [1, 2, 3, 4]L = [1, 2, 3, 4]

YesYes Can use other list forms as wellCan use other list forms as well

– [A, B, C, D] or [A, B, C | Tail], for example[A, B, C, D] or [A, B, C | Tail], for example

Page 10: 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),

ExerciseExercise

Show Prolog’s response…Show Prolog’s response…?- ?- [4, 3, 2, 1] = [H | T].[4, 3, 2, 1] = [H | T].

?- ?- [S, E, N, D | More] = [2, 4, 6, 8, 10].[S, E, N, D | More] = [2, 4, 6, 8, 10].

?- ?- [T, h, I, s] = [t, H, a, T].[T, h, I, s] = [t, H, a, T].

?- ?- [1, 2, 3 | More] = [X, Y, Z, Z, Y].[1, 2, 3 | More] = [X, Y, Z, Z, Y].

Page 11: 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),

Lists in TermsLists in Terms

Lists can be arguments in termsLists can be arguments in terms– a([1, 2, 3])a([1, 2, 3])– b(x, [w, e, r])b(x, [w, e, r])

And also any combinations thereofAnd also any combinations thereof– [a([1, 2, 3]), [b(x, [w, e, r]), c], d, e][a([1, 2, 3]), [b(x, [w, e, r]), c], d, e]

Page 12: 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),

Lists in ListsLists in Lists

A list can be an element of a listA list can be an element of a list [[a,b,c], [1,2,3], [do,re,mi]] has 3 elements[[a,b,c], [1,2,3], [do,re,mi]] has 3 elements

– first element is the list [a, b, c]first element is the list [a, b, c]– second element is the list [1, 2, 3]second element is the list [1, 2, 3]– third/last element is the list [do, re, mi]third/last element is the list [do, re, mi]

Can have lists in lists in lists as deep as you Can have lists in lists in lists as deep as you want – tho it can get hard to readwant – tho it can get hard to read– [a, [b], [[c,d], [e,f,g], [h,[[[[[i, j]]]]]]][a, [b], [[c,d], [e,f,g], [h,[[[[[i, j]]]]]]]

Page 13: 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),

Built-In Predicates for ListsBuilt-In Predicates for Lists

Find the length of a listFind the length of a list– length/2length/2

Ask if some element in a listAsk if some element in a list– member/2member/2

Add one list to the end of anotherAdd one list to the end of another– append/3append/3 conc/3 in the textconc/3 in the text

?-?- apropos(list). apropos(list). % for more% for more

Page 14: 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),

The Length of a ListThe Length of a List

Want to know how long a list isWant to know how long a list is

?- ?- length([1, 2, 3, 4], N).length([1, 2, 3, 4], N).N = 4N = 4YesYes Only counts Only counts top-leveltop-level elements elements?- length([a, [b, c, d], e], N).?- length([a, [b, c, d], e], N).N = 3N = 3YesYes

Page 15: 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),

The length/2 RelationshipThe length/2 Relationship

Can also generate list of desired lengthCan also generate list of desired length?- ?- length(L, 3).length(L, 3).L = [_G263, _G269, _G272]L = [_G263, _G269, _G272]YesYes length/2 is a relationshiplength/2 is a relationship

– between a list and a natural numberbetween a list and a natural number– holds if the list has that many elementsholds if the list has that many elements– not just for “counting elements”not just for “counting elements”

Page 16: 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),

Generating Every ListGenerating Every List

Can ask for any list of any lengthCan ask for any list of any length

?- ?- length(L, N).length(L, N).L = [], N = 0 L = [], N = 0 ;;L = [_G1], N = 1 L = [_G1], N = 1 ;;L = [_G1, _G2], N = 2 L = [_G1, _G2], N = 2 ;;L = [_G1, _G2, _G3], N = 3 L = [_G1, _G2, _G3], N = 3 ;;…… It’ll generate answers as long as you likeIt’ll generate answers as long as you like

Page 17: 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),

Printing Long ListsPrinting Long Lists

Prolog may not print all the elements of a Prolog may not print all the elements of a long listlong list– [1, 2, 3, 4, 5, 6, 7, 8, 9|…][1, 2, 3, 4, 5, 6, 7, 8, 9|…]– Saves space – easier to readSaves space – easier to read

If you want to see the whole thing:If you want to see the whole thing:– type type ww instead of space or semi-colon instead of space or semi-colon– (semi-)permanent change; type (semi-)permanent change; type pp to go back to go back– also applies when tracingalso applies when tracing

Page 18: 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),

List MembershipList Membership

We have some thing X and some list LWe have some thing X and some list L Want to know if X is in LWant to know if X is in L

?- ?- member(X, L).member(X, L). Note: looks only at the top-level elementsNote: looks only at the top-level elements

– member(b, [a, b, c]) member(b, [a, b, c]) succeedssucceeds– member(b, [a, [b, c], d]) member(b, [a, [b, c], d]) failsfails– member(b, list(a, b, c, d)) member(b, list(a, b, c, d)) failsfails

Page 19: 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),

Taking Elements One at a TimeTaking Elements One at a Time

member/2 will, as usual, fill in variables as member/2 will, as usual, fill in variables as required to get true answersrequired to get true answers

?- ?- member(X, [1, 2, 3]).member(X, [1, 2, 3]).

X = 1X = 1 ; ;

X = 2 X = 2 ;;

X = 3 X = 3 ;;

NoNo

member/2 is a relationshipholds between X and L if X is in L

Page 20: 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),

Filling In a ListFilling In a List

Variables are instantiated in the list itselfVariables are instantiated in the list itself

?- ?- member(3, [1, 2, X, 4]).member(3, [1, 2, X, 4]).X = 3X = 3YesYes?- ?- length(L, 2), member(1, L), member(2, L).length(L, 2), member(1, L), member(2, L).L = [1, 2] L = [1, 2] ;;L = [2, 1]L = [2, 1]YesYes

Page 21: 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),

member/2 Implemented in Prologmember/2 Implemented in Prolog

X is in the list if:X is in the list if:– it’s the head of the list, orit’s the head of the list, or– it’s in the tail of the listit’s in the tail of the list

?- ?- listing(member).listing(member).member(A, [A|B]).member(A, [A|B]).member(A, [B|C]) :-member(A, [B|C]) :-

member(A, C).member(A, C).

Recursive definitionCommon in predicates for lists

Page 22: 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),

member/2 Clausesmember/2 Clauses

Base case:Base case:– member(H, [H | _]).member(H, [H | _]).– first element of a list is a member of the listfirst element of a list is a member of the list– [H | _] is H followed by anything (pattern)[H | _] is H followed by anything (pattern)

Recursive caseRecursive case– member(E, [_ | T]) :- member(E, T).member(E, [_ | T]) :- member(E, T).– member of tail of list is member of listmember of tail of list is member of list

Page 23: 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),

ExerciseExercise

Show (all) Prolog’s responses…Show (all) Prolog’s responses…?- ?- length([1, 2, [3, 4], [5, 6]], N).length([1, 2, [3, 4], [5, 6]], N).

?- ?- length([1, 2, 3 | T], 4), member(5, T).length([1, 2, 3 | T], 4), member(5, T).

?- ?- length(L, 3), member(a, L), member(b, L).length(L, 3), member(a, L), member(b, L).

?- ?- member(a, [[X, Y]]), member(b, [[X, Y]]).member(a, [[X, Y]]), member(b, [[X, Y]]).

Page 24: 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),

List ConcatenationList Concatenation

Want to put two lists togetherWant to put two lists together Want to split a list in twoWant to split a list in two?- ?- append([1, 2, 3], [4, 5, 6], L).append([1, 2, 3], [4, 5, 6], L).L = [1, 2, 3, 4, 5, 6]L = [1, 2, 3, 4, 5, 6]YesYes?- ?- append(L1, L2, [1, 2, 3, 4, 5, 6]).append(L1, L2, [1, 2, 3, 4, 5, 6]).L1 = [], L2 = [1, 2, 3, 4, 5, 6] L1 = [], L2 = [1, 2, 3, 4, 5, 6] ;;L1 = [1], L2 = [2, 3, 4, 5, 6] L1 = [1], L2 = [2, 3, 4, 5, 6] ;;

Page 25: 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),

The append/3 RelationshipThe append/3 Relationship

append/3 can be used with any combination append/3 can be used with any combination of lists and variablesof lists and variables

It’s a It’s a relationshiprelationship between the three lists between the three lists Picture append(L1, L2, L3):Picture append(L1, L2, L3):

L1 L2

L3Doesn’t matter which one(s) you know ahead of time

Page 26: 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),

Pictures of ListsPictures of Lists

Making pictures of lists can help write codeMaking pictures of lists can help write code Does list L have three Does list L have three zzs together in it?s together in it?

?- ?- append(_, [z, z, z | _], L).append(_, [z, z, z | _], L).

1st sublist

L

_ z, z, z _

2nd sublist

Page 27: 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),

_

1st sublist

L

_

2nd sublist

Pictures of ListsPictures of Lists

Two sub-lists together make a longer listTwo sub-lists together make a longer list

Elements come at the front of Elements come at the front of some some listlist

?- ?- append(_, [z, z, z | _], L).append(_, [z, z, z | _], L).

z, z, z

Page 28: 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),

ExerciseExercise

Draw a picture & write a question to ask Draw a picture & write a question to ask whether a list L has two elements the same whether a list L has two elements the same togethertogether– [1, [1, 2, 22, 2, 3, 4] does, 3, 4] does– [1, [1, 22, 3, , 3, 22, 3] does not, 3] does not

Page 29: 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),

SolutionSolution

Picture and codePicture and code

?- ?- append(_, [X, X | _], L).append(_, [X, X | _], L).

1st sublist

L

_ X, X _

2nd sublist

Page 30: 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),

Question to PredicateQuestion to Predicate

Rewrite the query above as a predicate Rewrite the query above as a predicate doubled_element/2doubled_element/2– first argument is the listfirst argument is the list– second argument is the doubled elementsecond argument is the doubled element

doubled_element(L, X) :-doubled_element(L, X) :-

append(_, [X, X | _], L).append(_, [X, X | _], L). Works with values or variables everywhereWorks with values or variables everywhere

Page 31: 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),

ExerciseExercise

Draw a picture of a list that starts and ends Draw a picture of a list that starts and ends with the same elementwith the same element

Write a question that asks whether L has Write a question that asks whether L has this property (use append/3)this property (use append/3)

Translate the query into a predicate Translate the query into a predicate start_end/2start_end/2– 11stst arg. is list, 2 arg. is list, 2ndnd is start/end element is start/end element

Page 32: 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),

Other Predicates with ListsOther Predicates with Lists

Facts about listsFacts about listsmonths([jan, feb, mar, apr, may, jun, jul, aug, months([jan, feb, mar, apr, may, jun, jul, aug,

sep, oct, nov, dec]).sep, oct, nov, dec]).– this is a list of the months (in order!)this is a list of the months (in order!)

Rules with listsRules with listsis_month(M) :-is_month(M) :-

months(MonthList),months(MonthList),member(M, MonthList).member(M, MonthList).

Page 33: 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),

Note on EfficiencyNote on Efficiency

months/1 is a fact with one clausemonths/1 is a fact with one clause– only one solutiononly one solution

member/2member/2– two clauses – one fact, one rule (use listing/1)two clauses – one fact, one rule (use listing/1)– multiple solutionsmultiple solutions

Ask months/1 Ask months/1 firstfirst– apply facts earlyapply facts early– apply questions with less answers earlyapply questions with less answers early

Page 34: 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),

Note on StyleNote on Style

Having a months/1 predicate is (slightly!) Having a months/1 predicate is (slightly!) slower than hand coding list into is_monthslower than hand coding list into is_month

But it’s more generalBut it’s more general– can replace with full names…can replace with full names…– ……or with French, Spanish, …or with French, Spanish, …– use for other predicates that need monthsuse for other predicates that need months

Equivalent to declaring a constantEquivalent to declaring a constant– in style if not efficiencyin style if not efficiency

Page 35: 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),

Testing a ListTesting a List

Suppose have defined female/1 and male/1Suppose have defined female/1 and male/1 Check whether a list is all maleCheck whether a list is all male

% all_male(?L)% all_male(?L)% -- male(X) for each element X of L% -- male(X) for each element X of L Identify the predicate & its argument(s)Identify the predicate & its argument(s)

– we’ll talk about the ? soonwe’ll talk about the ? soon State the relationship/property that holdsState the relationship/property that holds

Page 36: 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),

Logic of List TestingLogic of List Testing

Every element is maleEvery element is male Going to use recursion (no loops!)Going to use recursion (no loops!) Base caseBase case

– ?????? Recursive caseRecursive 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?

Page 37: 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),

All MalesAll Males

% all_male(?L)% all_male(?L)%% -- male(X) for all elements X of L-- male(X) for all elements X of L

all_male([]).all_male([]).all_male([H | T]) :-all_male([H | T]) :-

male(H),male(H),all_male(T).all_male(T).

Page 38: 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),

General List UseGeneral List Use

Common to want to do stuff with every Common to want to do stuff with every element of a listelement of a list– test it, make a copy of it, …test it, make a copy of it, …

Multi-clause predicate (usually 2)Multi-clause predicate (usually 2)– first clause is base case (usually 0 or 1 element)first clause is base case (usually 0 or 1 element)– last clause recursive case (extracts head, recurs last clause recursive case (extracts head, recurs

on tail)on tail)– extra cases as requiredextra cases as required

Page 39: 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),

On ?, + and – On ?, + and –

Documented argument with ? in front of itDocumented argument with ? in front of it– means that arg. can be variable or valuemeans that arg. can be variable or value

Alternatives are +Alternatives are +– shouldshould have a value have a value– unboundunbound variables not allowed/bad idea variables not allowed/bad idea

And –And –– should should notnot have a value have a value– unbound variables unbound variables onlyonly

“bound” = has a value other than just another variable

Used in system documentationsee help(member), help(is)

Page 40: 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),

ExerciseExercise

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

Document itDocument it

Page 41: 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),

Case AnalysisCase Analysis

Simplest list is the empty listSimplest list is the empty list If the first list is empty, what should the If the first list is empty, what should the

second list be?second list be?

If the first list is not empty, how is the head of If the first list is not empty, how is the head of the second list related to the head of the first?the second list related to the head of the first?

How are the tails related?How are the tails related?

Page 42: 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),

DocumentationDocumentation

How is the second list related to the first?How is the second list related to the first? What notations on the arguments?What notations on the arguments?

– ????– +?+?– ––??

What shall we call the arguments?What shall we call the arguments?

Page 43: 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),

Possible SolutionPossible Solution

% one_more(+Less, ?More)% one_more(+Less, ?More)%% -- N is M+1 for each N in More-- N is M+1 for each N in More%% and the corresponding M in Less and the corresponding M in Less

one_more([], []).one_more([], []).one_more([M | Ms], [N | Ns]) :-one_more([M | Ms], [N | Ns]) :-

N is M + 1,N is M + 1,one_more(Ms, Ns).one_more(Ms, Ns).

Page 44: 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),

Logical AdditionLogical Addition

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

plus(M, 1, N),plus(M, 1, N),one_more(Ms, Ns).one_more(Ms, Ns).

% M + 1 is equal to N

Page 45: 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),

Miscellaneous Math StuffMiscellaneous Math Stuff

Logical additionLogical addition ((will fill in any one variablewill fill in any one variable))– plus(X, Y, Z)plus(X, Y, Z) X + Y is equal to Z X + Y is equal to Z– succ(M, N)succ(M, N) M + 1 is equal to N M + 1 is equal to N

Comparisons Comparisons ((variables must be boundvariables must be bound))– M < N, N < PM < N, N < P M < N & N < P M < N & N < P– M =< N, N >= PM =< N, N >= P M M N & N N & N P P– N \= PN \= P N N P P

Page 46: 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),

By Cases in PrologBy Cases in Prolog

Suppose we want to write larger/3Suppose we want to write larger/3– 33rdrd argument is larger of 1 argument is larger of 1stst two two

Two cases:Two cases:– first argument is larger than secondfirst argument is larger than second– first argument is less than or equal to secondfirst argument is less than or equal to second

%% larger(+First, +Second, ?Larger)%% larger(+First, +Second, ?Larger)

larger(First, Second, First) :- First > Second.larger(First, Second, First) :- First > Second.

larger(First, Second, Second) :- First =< Second.larger(First, Second, Second) :- First =< Second.

Page 47: 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),

ExerciseExercise

Write a predicate all_leq/2Write a predicate all_leq/2– each element of the first list is less than or each element of the first list is less than or

equal to the corresponding element of the equal to the corresponding element of the secondsecond

– (also, lists are the same length)(also, lists are the same length)?- ?- all_leq([1, 2, 3, 4], [1, 2, 3, 5]).all_leq([1, 2, 3, 4], [1, 2, 3, 5]).YesYes?- ?- all_leq([1, 2, 3, 4, 5], [7, 6, 5, 4, 3]).all_leq([1, 2, 3, 4, 5], [7, 6, 5, 4, 3]).NoNo

Page 48: 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),

Getting Elements by PositionGetting Elements by Position

last/2 queries last element of a listlast/2 queries last element of a list nth1/3 queries nth element of a listnth1/3 queries nth element of a list

– starts counting at 1starts counting at 1 nth0/3 queries nth element of a listnth0/3 queries nth element of a list

– starts counting at 0starts counting at 0

?- ?- last(_Last, [a, c, e]), nth0(1, [a, c, e], _Second), last(_Last, [a, c, e]), nth0(1, [a, c, e], _Second), nth1(2, L, _Second), nth1(1, L, _Last).nth1(2, L, _Second), nth1(1, L, _Last).

L = [e, c | _G1]L = [e, c | _G1]

Page 49: 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),

Insertion and DeletionInsertion and Deletion

Insertion to & deletion from listsInsertion to & deletion from lists– just oppositesjust opposites– three way relationshipthree way relationship– shorter list, extra element, longer listshorter list, extra element, longer list– use same predicate for bothuse same predicate for both– select/3 in SWI-Prologselect/3 in SWI-Prolog

Page 50: 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),

Using select/3Using select/3

To delete an elementTo delete an element?- ?- select([g, o, n, e], n, L).select([g, o, n, e], n, L).L = [g, o, e]L = [g, o, e]

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

Page 51: 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),

Using select/3Using select/3

Deleting any elementDeleting any element?- ?- select([a, b, c], X, Rest).select([a, b, c], X, Rest).X = a, Rest = [b, c] X = a, Rest = [b, c] ;;X = b, Rest = [a, c] X = b, Rest = [a, c] ;;X = c, Rest = [a, b] X = c, Rest = [a, b] ;;NoNo

Page 52: 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),

Using select/3Using select/3

To insert into a given position (1-based)To insert into a given position (1-based)?-?- nth1(3, L, n), select(L, n, [g, o, e]). nth1(3, L, n), select(L, n, [g, o, e]).L = [g, o, n, e]L = [g, o, n, e]YesYes

Exercise: change that into a predicateExercise: change that into a predicate%% insertKth(Old, Kth, Value, New)%% insertKth(Old, Kth, Value, New)%% New is Old with Value inserted into Kth New is Old with Value inserted into Kth

placeplace%% (first element of list = position 1)(first element of list = position 1)

Page 53: 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),

Next TimeNext Time

Using Structures and ListsUsing Structures and Lists