Chapter 7 - Working with lists in Prolog Flashcards
Lists
symbolic structures; sequence of objects that are called elements
Lists can help to..
write clauses for predicates that are very similar except for the number of arguments they take
Valid lists examples in Prolog
[anna,karenina]
[john,paul,george,ringo,zeppo]
[1,2,3,3,2,1]
[]
Can lists contain other lists aswell?
Yes:
[[john,23],[mary,14],[hello]]
[8,john,[’199y’,john]]
[[]]
Is a one element list different from the element itself?
Yes:
[anna] is different from anna ;
[[]]is different from[].
Head
First element of a non-empty list. Can be anything.
Tail
list that is formed by removing the first element from a list
[a,b,c,d] has head a and tail[b,c,d];
[[a],b,[c]] has head [a] and tail [b,[c]];
[a,[b,c]] has head a and tail [[b,c]];
A tail MUST be a list
Prolog term
Constant, variable, number and LIST
Two ways for Prolog to write lists:
- A left square parenthesis, followed by a sequence of terms separated by commas and terminated by a right square parenthesis.
- A left square parenthesis, followed by a nonempty sequence of terms separated by commas, followed by a vertical bar, followed by a term denoting a list, and terminated by a right square parenthesis.
List –> [X|Y, Z]
list who head is X and whose tail is the list with head Y and tail Z.
Are [1 , X , 3 | [ ] ] and [1,X,3] the same list?
Yes
Unification with lists
- Two lists without variables are considered to unify when they are identical, element for element.
- Two lists with distinct variables are considered to unify when the variables can be given values that make the two lists identical, element for element.
Not-unification with lists
Lists will not unify if they have different numbers of elements or if at least one corresponding element does not unify.
Unification with lists take-away
X matches anything, including any list.
[X] matches any list with exactly one element.
[X|Y] matches any list with at least one element.
[X,Y] matches any list with exactly two elements.
What will the following query output?
member(X,[a,b,c]).
X=a ;
X=b ;
X=c ;
No