Guest User

Untitled

a guest
Aug 10th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 2.16 KB | None | 0 0
  1. teacher(tom).
  2. teacher(X) :- wise(X), old(X).
  3. teacher(X) :- likes(Y,X), !, minister(Y).
  4.  
  5. wise(X) :- hasBeard(X).
  6.  
  7. old(tom).
  8. old(alice).
  9.  
  10. hasBeard(tom).
  11. hasBeard(john).
  12. hasBeard(bill).
  13.  
  14. minister(x).
  15. likes(alice,bob).
  16. likes(x,bob).
  17.  
  18.  
  19.  
  20.  
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22.  
  23. %not(Goal) :- Goal,!,fail.
  24. %not(_).
  25.  
  26. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  27. % an interesting application which can be solved using Prolog is Constraint Satisfaction
  28.  
  29. % Assume we have a variable X, a set of possible values for X (i.e. a domain D, expressed in Prolog as a list), and a constraint C over X. Let us write a predicate:
  30. % csp1(X,D,E,C) such that, for X, D, and C given, D would be bound to a list of values for which C is satisfied.
  31. % example: csp1(X,[9,2,3,4,5,6],E,X>1).
  32.  
  33. csp1(_,[],[],_).
  34.  
  35. csp1(X,[DH|DT],E,C) :- X is DH, C, !, csp1(X,DT,E1,C), E = [DH|E1].
  36. csp1(X,[DH|DT],E,C) :- X is DH, not(C), !, csp1(X,DT,E,C).
  37.  
  38. %let us test this implementation using trace
  39. %it is straightforward that our problem is that X is bound to the first value from DH, and remains bound to it. How can we solve the problem ?
  40.  
  41. %the negation, discussed previously, offers a hint:
  42. csp2(_,[],[],_).
  43. csp2(X,[DH|DT],E,C) :- not((X is DH, C)), csp2(X,DT,E,C).
  44. csp2(X,[DH|DT],E,C) :- csp2(X,DT,E1,C), E = [DH|E1].
  45.  
  46. %everything appears to be ok, yet still there is another problem. When D = [1,2,3,4,5,6], the goal not((X is 1, C)) is satisfied. However, Prolog tries to resatisfy it, using the second clause (which does not explicitly mention that not((X is 1, C)) is not satisfied.
  47.  
  48. %a possible alternative to this issue is:
  49. csp3(_,[],[],_).
  50. csp3(X,[DH|DT],E,C) :- not((X is DH, C)), csp3(X,DT,E,C).
  51. csp3(X,[DH|DT],E,C) :- not(not((X is DH, C))), csp3(X,DT,E1,C), E = [DH|E1].
  52.  
  53. %however this approach is cumbersome. A more elegant implementation is:
  54.  
  55. csp4(_,[],[],_).
  56. csp4(X,[DH|DT],E,C) :- csp4(X,DT,E1,C), (not((X is DH, C)), E=E1, !; E = [DH|E1]).
  57.  
  58. %which can be read: try to satisfy (recursively) csp4(X,DT,E1,C). After doing so, if the condition C is not satisfied for DH, unify E with E1 and stop any attempt to resatisfy the goal. Otherwise (C is satisfied for X is DH), unify E with [DH|E1].
Add Comment
Please, Sign In to add comment