Beruflich Dokumente
Kultur Dokumente
Barbara Morawska
April 1, 2019
Lists in Prolog
Examples:
I list of characters: [a, b, c]
I list of numbers: [17, 13, 11, 7, 5, 3, 2]
I list of strings (repetitions) [orange, orange, apple, banana]
I list with elements not of the same type [X , f (A), hello, 3, −9.4]
I list containing lists [a, [a, a], [a, [a, a]], a]
I list with the empty list [the, [], has, nothing , in, it]
List constructor
[Head | Tail]
where Head is the first element of the list and Tail is the rest of the list
The query: ?-[Head | Tail] = [a,b,c]
returns: Head = a, Tail = [b,c]
Construct a list: ?- A = a, B = [b, c], C = [A|B].
List exercise
Try the following goals:
?- [a] = [H|T].
?- [ ] = [H|T].
What happens?
String in double quotes
String in double quotes: ”abcd” is treated as a list of ASCII characters.
Try queries:
?- "abcd"=X. X = ”abcd”
?- "abcd" = [97, 98, 99, 100]. false
?- "abcd" = [H|T]. false
?- "X*(Y+Z)" = [H|T] false
p([]).
p([a,a|X]) :- p(X).
Y^p(X,Y)
which is equal to ∃Y p(X , Y ).
What is S?
Defining sets in Prolog
I Define set S = {x | p(a, x)} in Prolog.
I setof(X,p(a,X),S).
I What is S now?
I Define a set of grandparent relations:
S = {g (X , Y ) | ∃Z (p(X , Z ) ∧ p(Z , Y ))}
I setof(g(X,Y), Z^(p(X,Z), p(Z,Y)),S)
Bags (multisets) in Prolog
A bag (multiset) is a set in which repetitions are allowed.
Example
Define a bag of first elements of the parent relation.
I what is S now?
I Compare it with setof predicate.
member(H, [H|_]).
Subset
Using member predicate we can define subset predicate
subset([ ], _).
S = A ∪ B = {x | x ∈ A ∨ x ∈ B}
S = A ∩ B = {x | x ∈ A ∧ x ∈ B}
S = A −̇ B = (A \ B) ∪ (B \ A)
S = A −̇ B = (A ∪ B) \ (A ∩ B)
my_length([Head | Tail], L) :- . . .
I Define predicate concatenate for two lists, that computes their
concatenation:
concatenate([h,e], [l,l,o], A)
should yield A = [h, e, l, l, o]
Do not use the predefined predicate append that does it.
I Define predicate last, that finds the last element of a nonempty list.
I Define predicate pairs that finds the list of pairs of the elements of
two lists of the same length. Given two lists: [a, b, c] and [1, 2, 3] it
returns [[a, 1], [b, 2], [c, 3]]
Exercises
I Define a predicate pairs1 that given an element and a list creates
pairs with this element. Given an element a and a list [1, 2, 3] it
creates [[a, 1], [a, 2], [a, 3]].
I Define a predicate prod that given two lists created the Cartesian
product of them.
I Define a predicate replace that given a list will replace one element
by another. For example:
replace(a, o, [b, a, n, a, n, a], X).
Should yield: X = [b, o, n, o, n, o]
I Define a predicate powerset that given a list, will construct a list
containing all subsets of the elements in the list. For example:
?- powerset([a, b], X).
should yield: X = [[], [a], [b], [a, b]]