List Manipulation in Prolog A Nonlist Example Prologs

  • Slides: 10
Download presentation
List Manipulation in Prolog A Non-list Example Prolog's List notation List manipulation techniques Append

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 1

Example % courses. pl Some prerequisite relationships prereq(cse 142, cse 143). prereq(cse 143, cse

Example % courses. pl Some prerequisite relationships prereq(cse 142, cse 143). prereq(cse 143, cse 341). prereq(cse 341, cse 473). before(X, Y) : - prereq(X, Y). before(X, Y) : - prereq(X, Z), before(Z, Y). CSE 341 -- S. Tanimoto Lists in Prolog 2

A Session ? - consult(courses). % courses compiled 0. 00 sec, 1, 088 bytes

A Session ? - consult(courses). % courses compiled 0. 00 sec, 1, 088 bytes Yes ? - prereq(cse 142, cse 143). Yes ? - prereq(cse 142, X). X = cse 143 ; No CSE 341 -- S. Tanimoto Lists in Prolog 3

A session (cont) ? - prereq(X, Y). X = cse 142 Y = cse

A session (cont) ? - prereq(X, Y). X = cse 142 Y = cse 143 ; X = cse 143 Y = cse 341 ; X = cse 341 Y = cse 473 ; No ? - CSE 341 -- S. Tanimoto Lists in Prolog 4

A session (cont) ? - before(X, cse 341). X = cse 143 ; X

A session (cont) ? - before(X, cse 341). X = cse 143 ; X = cse 142 ; No CSE 341 -- S. Tanimoto Lists in Prolog 5

Lists in Prolog colors([r, g, b]). ? - colors(L). L = [r, g, b]

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 6

Defining Predicates on Lists car([X|L], X). cdr([X|L], L). cons(X, L, [X|L]). ? - car([a,

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

concat a. k. a. append concat([], L, L). concat([X|L 1], L 2, [X|L 3])

concat a. k. a. append concat([], L, L). concat([X|L 1], L 2, [X|L 3]) : - concat(L 1, L 2, L 3). ? - 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 8

concat used backwards ? - concat(X, Y, [x, y, z]). X = [] Y

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 9

Logic Prog. vs Functional Prog. Functional programming: evaluation is one-way. Logic programming: evaluation can

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 10