90 likes | 214 Views
Manipulating Terms More Generally. functor(Term, F, A) succeeds if Term has principal functor F and arity A. Goal:. Result:. functor(foo(a,b,c), F, A) functor(foo(a,b(X)), F, A) functor([a,b,c], F, A) functor(bar, F, A). F = foo, A = 3. F = foo, A = 3. F = ‘.’, A = 2.
E N D
Manipulating Terms More Generally functor(Term, F, A) succeeds if Term has principal functor F and arity A. Goal: Result: functor(foo(a,b,c), F, A) functor(foo(a,b(X)), F, A) functor([a,b,c], F, A) functor(bar, F, A) F = foo, A = 3 F = foo, A = 3 F = ‘.’, A = 2 F = bar, A = 0
Manipulating Terms More Generally Term =.. [ F | T ] succeeds if Term has principal functor F and argument list T. Goal: Result: foo(a,b,c) =.. X foo(a,b(X)) =.. X [a,b,c] =.. X bar =.. X X = [foo,a,b,c] X = [foo,a,b(X)] X = [‘.’,a,[b,c]] X = [bar]
Operators Goal: Result: current_op(A, P, ‘+’) current_op(A, P, ‘-’) current_op(A, P, ‘*’) A = yfx, P = 500 A = yfx, P = 500 A = yfx, P = 400 - display(1 + 2 * 3 – 4) + 4 -( +( 1, *( 2, 3 ) ), 4) 1 * 2 3
Complete Set of Associativities \+ fx fy ‘:-’ \+ ‘,’ :- a, b \+ \+ a a b a yfx xfy + ‘,’ 1 + (a, b, c) ‘,’ c 1 + 2 + 3 3 2 a b
Defining Your Own Operators :- op(800, xfy, and), op(810, xfy, '==>'). skin(X, hairy) and not(colour(X, red)) ==> toxicity(X, low). colour(X, red) ==> toxicity(X, high). skin(X, smooth) and colour(X, brown) ==> toxicity(X, low). skin(X, smooth) and not(colour(X, brown)) ==> toxicity(X, high). toxicity(X, low) ==> eat(X). toxicity(X, high) ==> avoid(X). These are not built-in operators in Prolog so they need to be defined
Writing an Interpreter bsearch(Facts, Goal):- member(Goal, Facts). bsearch(Facts, G1 and G2):- bsearch(Facts, G1), bsearch(Facts, G2). bsearch(Facts, not(Goal)):- \+ bsearch(Facts, Goal). bsearch(Facts, Goal):- Preconditions ==> Goal, bsearch(Facts, Preconditions). Goal: Result: bsearch([skin(f1, smooth),colour(f1,brown)], eat(X)) X = f1
A Prolog Interpreter in Prolog solve(true). solve((A,B)) :- solve(A), solve(B). solve((A;B)) :- solve(A) ; solve(B). solve(\+ A) :- \+ solve(A). solve(A) :- clause(A, B), solve(B).
Extending the Interpreter: Depth Limit solve(true, _). solve((A,B), D) :- solve(A, D), solve(B, D). solve((A;B), D) :- solve(A, D) ; solve(B, D). solve(\+ A, D) :- \+ solve(A, D). solve(A, D) :- D > 0, D1 is D -1, clause(A, B), solve(B, D1).
Extending the Interpreter: Explanation solve(true, t). solve((A,B), a(EA,EB)) :- solve(A, EA), solve(B, EB). solve((A;B), E) :- solve(A, E) ; solve(B, E). solve(\+ A, not(A)) :- \+ solve(A, _). solve(A, rule(A,E)) :- clause(A, B), solve(B, E).