List Manipulation in Prolog A Non-list Example Prolog's List notation List manipulation techniques Append Running definitions forwards and backwards CSE 341 -- S. Tanimoto Lists in Prolog
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 341 -- S. Tanimoto Lists in Prolog
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 341 -- S. Tanimoto Lists in Prolog
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 341 -- S. Tanimoto Lists in Prolog
CSE 341 -- S. Tanimoto Lists in Prolog A session (cont) ?- before(X, cse341). X = cse143 ; X = cse142 ; No CSE 341 -- S. Tanimoto Lists in Prolog
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 341 -- S. Tanimoto Lists in Prolog
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 341 -- S. Tanimoto Lists in Prolog
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 341 -- S. Tanimoto Lists in Prolog
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 341 -- S. Tanimoto Lists in Prolog
Logic Prog. vs Functional Prog. Functional programming: evaluation is one-way. Logic programming: evaluation can be two-way. CSE 341 -- S. Tanimoto Lists in Prolog