Presentation is loading. Please wait.

Presentation is loading. Please wait.

List Manipulation in Prolog

Similar presentations


Presentation on theme: "List Manipulation in Prolog"— Presentation transcript:

1 List Manipulation in Prolog
A Non-list Example Prolog's List notation List manipulation techniques Append Running definitions forwards and backwards CSE S. Tanimoto Lists in Prolog

2 CSE 341 -- S. Tanimoto Lists in Prolog
Example % courses.pl Some prerequisite relationships prereq(cse142, cse143). prereq(cse143, cse341). prereq(cse341, cse473). before(X, Y) :- prereq(X, Y). before(X, Y) :- prereq(X, Z), before(Z, Y). CSE S. Tanimoto Lists in Prolog

3 CSE 341 -- S. Tanimoto Lists in Prolog
A Session ?- consult(courses). % courses compiled 0.00 sec, 1,088 bytes Yes ?- prereq(cse142, cse143). ?- prereq(cse142, X). X = cse143 ; No CSE S. Tanimoto Lists in Prolog

4 CSE 341 -- S. Tanimoto Lists in Prolog
A session (cont) ?- prereq(X, Y). X = cse142 Y = cse143 ; X = cse143 Y = cse341 ; X = cse341 Y = cse473 ; No ?- CSE S. Tanimoto Lists in Prolog

5 CSE 341 -- S. Tanimoto Lists in Prolog
A session (cont) ?- before(X, cse341). X = cse143 ; X = cse142 ; No CSE S. Tanimoto Lists in Prolog

6 CSE 341 -- S. Tanimoto Lists in Prolog
colors([r, g, b]). ?- colors(L). L = [r, g, b] ?- colors([X|Y]). X = r, Y = [g, b] % X is the head. Y is the tail. ?- mylist([a, [b, c]]). CSE S. Tanimoto Lists in Prolog

7 Defining Predicates on Lists
car([X|L], X). cdr([X|L], L). cons(X, L, [X|L]). ?- car([a, b, c], X). X = a ?- cdr([a, b, c], X). X = [b, c] ?- cons(a, [b, c], X). X = [a, b, c] CSE S. Tanimoto Lists in Prolog

8 CSE 341 -- S. Tanimoto Lists in Prolog
concat a.k.a. append concat([], L, L). concat([X|L1], L2, [X|L3]) :- concat(L1, L2, L3). ?- concat([a, b, c], [d, e], X). X = [a, b, c, d, e] ?- concat(X, [d, e], [a, b, c, d, e]). X = [a, b, c] CSE S. Tanimoto Lists in Prolog

9 CSE 341 -- S. Tanimoto Lists in Prolog
concat used backwards ?- concat(X, Y, [x, y, z]). X = [] Y = [x, y, z] ; X = [x] Y = [y, z] ; X = [x, y] Y = [z] ; X = [x, y, z] Y = [] ; No CSE S. Tanimoto Lists in Prolog

10 Logic Prog. vs Functional Prog.
Functional programming: evaluation is one-way. Logic programming: evaluation can be two-way. CSE S. Tanimoto Lists in Prolog


Download ppt "List Manipulation in Prolog"

Similar presentations


Ads by Google