ChrisK
ChrisK

Reputation: 184

Prolog - Describe facts and rules

I want to describe in prolog the following facts and rules:

  1. Nick is programming in Java.
  2. Nick is programming in Python
  3. Nick is friend with anyone that is programming in Java and Python
  4. Jim is programming in all languages that Nick does.

I found the solution for 1, 2 and 3 but not for the 4th, even though i would really appreciate a full solution.

My solution:

male(Nick).

male(Jim).

programming(Nick, java).

programming(Nick, python).

friends(X,Y):-
    programming(X,java),
    programming(X,python),
    programming(Y,java),
    programming(Y,python),

Upvotes: 3

Views: 847

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

There are a few errors in your solution:

  • A constant (like Nick) starting with a capital letter is no constant; but a variable. Thus the line:

    male(Nick).
    

    says that everyone is a male/1; you should correct it to:

    male(nick).
    male(jim).
    

    (the same for programming/2 by the way). furthermore this doesn't seem to be part of the assignment (?).

  • The friends/2 predicate ends with a comma (,) meaning that the Prolog parser expects more input, and will see the next fact as part of the current clause; you should end clauses with the dot (.);

  • The friends/2 predicate is not semantically correct, since the question only makes statements about Nick: you thus can't use X as the person, you should specialize it like:

    friends(nick,Y):-
        programming(Y,java),
        programming(Y,python).
    

    Your version of friends/2 said: "A person X is a friend of a person Y, if both X and Y can program in Java and Python"; although this results in the fact that Nick is a friend of everyone that programs in Java and Python, your statements is broader than what should be allowed: we don't know if Jim for instance decides who is friends with him based on these rules. It is for instance possible (although perhaps not likely) that Jim wants to learn things from his friends, and for instance is only friends with people that know at least one programming language he doesn't master.

  • The last question can be written as:

    programming(jim,X) :-
        programming(nick,X).
    

    an almost mechanical translation of the statement is: "Jim is programming in X if nick is programming in X"; (mind this is no if-and-only-if); so you can still add additional languages Jim can work with.

Upvotes: 3

Related Questions