A Introduction to Prolog!

female(X) :- \+ male(X).
brother(X,Y) :- parent(P,X), parent(P,Y), male(X), X \= Y.
ancestors(As,X) :- setof(A,ancestor(A,X),As).

setof/3 can be useful if you want to find all the solutions of a predicate. For example if we have this database :

If we want to find all the solutions of knows(X,Y). we can enter :
     Z = [[jim,fred],[alf,bert]]
The followings are legal atoms :
The followings are not legal atoms :
     two words
You can use single quotes to make any character combination a legal atom.
     'two words'
The number of arguments is the arity of the predicate. A predicate with 2 arguments will be called by predicate_name/2. You can have different predicates with the same name if they have a different arity.

Another very useful list predicate builds lists from other lists or alternatively splits lists into separate pieces. This predicate is usually called append. In this predicate the second argument is appended to the first argument to yield the third argument. For example
     ?- append([a,b,c],[d,e,f],X).
     X = [a,b,c,d,e,f]
It is a little more difficult to follow, since the basic strategy of working from the head of the list does not fit nicely with the problem of adding something to the end of a list. append solves this problem by reducing the first list recursively. The boundary condition states that if a list X is appended to the empty list, the resulting list is also X.
The recursive condition states that if list X is appended to list [T|Q1], then the head of the new list is also H, and the tail of the new list is the result of appending X to the tail of the first list.
     append([T|Q1],X,[T|Q2]) :- append(Q1,X,Q2).
Real Prolog magic is at work here, which the trace alone does not reveal. At each level, new variable bindings are built, that are unified with the variables of the previous level. Specifically, the third argument in the recursive call to append is the tail of the third argument in the head of the clause. These variable relationships are included at each step. 

How to add a rule with a program

It is possible to add new rules or facts with the instruction Assert(fact1) which will add the fact called fact1. The predicates added with this command are considered like any other in the source of the program.

The instructions

The useful instructions are :
assert(c). Add the rule c in the database.assert()
retract(c). Remove the c from the database.retract(c)
asserta(c). Add c at the beginning of the database.asserta()
assertz(c). Add c at the end of the database.assertz()


     ?- sunny.
     ?- assert(sunny).
     ?- sunny.

     ?- retract(sunny).

     ?- sunny.