Prolog Exercises

  1. Consider the following Prolog program.
    rich(john).
    healthy(john).
    healthy(tim).
    happy(X) :- rich(X), healthy(X).
    
    These statements encode the facts that John is rich, John and Tim are both healthy, and everyone who is both healthy and rich is also happy. Create a new Prolog file that encodes the following:
    • John is rich.
    • John is healthy.
    • Tim is healthy.
    • John likes Tim.
    • If a person likes someone, then that person likes them back.
    • Anyone who is rich, healthy and liked will be happy.
    Load the resulting Prolog program, and construct queries to check whether Tim is happy, whether John is happy, and asking for a listing of all happy people. Does anything strange happen?
  2. The following pair of rules is sufficient for checking membership in a Prolog list:
    in(X, [X | T]).
    in(X, [H | T]) :- in(X, T).
    
    Load these rules, and try them out with a few queries. Then create a new set of rules to that can check to see if an item appears in two consecutive locations in a list. Example queries might look like the following:
    | ?- in_double(c, [a, b, c, c, d]).
    
    true ? 
    
    yes
    | ?- in_double(c, [a, b, c, d]).   
    
    no
    | ?- in_double(b, [a, X, X, c, d]).
    
    X = b ? 
    
    yes
    
  3. If you have time, write and test rules for in2, which should check to see if an item appears at least twice anywhere in a list.