70 likes | 190 Views
Chapter Two: (cont.) Syntax and Meaning of Prolog Programs. 2.2 Matching. Matching is the most important operation on terms . Given two terms, they match if: they are identical, or
E N D
2.2 Matching • Matching is the most important operation on terms. • Given two terms, they match if: • they are identical, or • the variables in both terms can be instantiated to objects in such a way after the substitution of variables by these objects the terms become identical. Example date(D, M, 2001) and date(D1, may, Y1) date(D, M, 2001) and date(D1, M1, 1444) date(X, Y, Z) and point(X, Y, Z)
The general rules to decide weather two terms match • If S and T are constantsthen S and T match onlyifthey are thesameobject. • If S is a variable and T isanything, thenthey match, and S isinstantiatedto T. (And vice versa) • If S and T are structuresthenthe match onlyif: • S and T havethesameprinciplefunctor, and • Alltheircorrespondingcomponents match.
2.2 Matching • Matching is a process that takes as inputs two terms and check whether they match. If the terms do not match, we say this process fails. If they match, the process succeeds. • To request Prolog matching operation, we use ‘=‘ : ?- parent(X, anna)= parent (bob, Y). Prolog Answer : X = bob Y = anna yes
2.2 Matching Example Consider the following terms in Prolog program: point (_, _). seg(point(_,_), point(_,_)). triangle(point(_,_), point(_,_), point(_,_)). Declare vertical and horizontal relations vertical (seg(point(X,_), point(X,_))). horizontal (seg(point(_,Y), point(_,Y))).
2.2 Matching Formulate the following questions and find Prolog answers: • Is the segment (1,1), (1,4) vertical? ?- vertical (seg(point(1,1), point(1,4))). Prolog Answer : yes • What is the other coordinate that make the segment (1,1), (2,Y) vertical? ?- vertical (seg(point(1,1), point(2,Y))). Prolog Answer : no
2.2 Matching • What is the other coordinate that make the segment (1,1), (2,Y) horizontal? ?- horizontal (seg(point(1,1), point(2,Y))). Prolog Answer : Y=1 • Are there any vertical segment that start at point(2,3)? ?- vertical (seg(point(2,3), point(_,_))). Prolog Answer : yes • Is there a segment that is both vertical and horizontal? ?- vertical (S), horizontal (S). Prolog Answer : S = seg(point(X,Y), point(X,Y)) yes