Wednesday, August 10, 2016

Some Common Prolog Programs to get started


/* Sum of Natural Numbers*/
sum(N):-
  sumcalc(N,S),
  write('The sum of natural numbers is '),write(S),nl.
sumcalc(0,0).
sumcalc(N,S):-
   N>0,
   N1 is N-1,
   sumcalc(N1,S1),
   S is N+S1.
/** The Recursionn can be traced as follows::
* sum(5)
* sumcalc(5,S)
*  sumcalc(4,S)
*   sumcalc(3,S)
*    sumcalc(2,S)
*     sumcalc(1,S)
*      sumcalc(0,S):-sumcalc(0,0)
*      S is 0
*     S is 1+0=1
*    S is 2+1=3
*   S is 3+3=6
*  S is 4+6=10
* S is 5+10=15 
*/


/* Factorial */
fact(N):-factcal(N,F),write('Factorial is '),write(F),nl.
factcal(0,1).
factcal(N,F):-
   N>0,
   N1 is N-1,
   factcal(N1,F1),
   F is N*F1.

/** The Recursion can be traced as follows::
* fact(3)
* factcal(3,F)
*  factcal(2,F)
*   factcal(1,F)
*    factcal(0,F):-factcal(0,1)
*    F is 1
*   F is 1*1=1
*  F is 2*1=2
* F is 3*2=6
*/ 


/**
* Rabbits run faster than Cats, Cats run faster than Dogs.
* Do Rabbits run faster than Dogs?
*/
runfaster(rabbits, cats).
runfaster(cats,dogs).
runfastest(X,Y):-runfaster(X,Z),runfaster(Z,Y).
runfaster(A,B):-runfastest(A,B).


/**
* X is larger than Y. 
* Y is larger than Z, 
* A is larger than Z and smaller than Y.
* Check which one is smaller among A and X.
*/
larger(x,y).
larger(y,z).
larger(a,z).
larger(y,a).
larger(x,z):-larger(y,z).
larger(x,a):-larger(x,y),larger(x,z).


/**
* Write a prolog program to display definition of AI
*/
define(A):-
write(A),write(' is deined as something that:'),nl,
write('has ability to think like human'),nl,
write('has ability to act like human'),nl,
write('has ability to think rationally'),nl,
write('had ability to act rationally'),nl.


/** WAP to find:
* a. Sum of 3 numbers 
* b. Difference between any two numbers
* c. Sum of squares of any two numbers 
* d. Simple interest
*/
findsum(A,B,C):-S is A+B+C, write('The sum is '),write(S),nl.
difference(A,B):-D is A-B, write('The difference is '),write(D),nl.
sumofsq(A,B):-Q is A*A+B*B,write('The SoSq is '),write(Q),nl.
si(P,T,R):-X is P*T*R,
           I is X/100, 
           write('Simple Interest is '),write(I),nl.


/* Show if path is available for given graph */
edge(s,a).
edge(a,s).
edge(s,b).
edge(b,s).
edge(a,c).
edge(c,a).
edge(b,d).
edge(d,b).
edge(a,d).
edge(d,a).
path(X,Y):-edge(X,Y);
            (edge(X,Z),edge(Z,Y));
            (edge(X,Z),edge(Z,W),edge(Z,W),edge(W,Y)).


/**
* Ram is  son of Raj.
*  Sony is mother of Ram and
*  Ramsy is sister of Ram.
*/
male(ram).
male(raj).
female(sony).
female(ramsy).
siblings(ram,ramsy).
siblings(X,Y):-siblings(Y,X).
son(ram,raj).
son(X,Y):-male(X),(father(Y,X);mother(Y,X)).
mother(sony,ram).
mother(X,Y):-female(X),(son(Y,X);(siblings(Y,Z),son(Z,X))).
sister(X,Y):-female(X),(siblings(X,Y);siblings(Y,X)).
brother(X,Y):-male(X),(siblings(X,Y);siblings(Y,X)).
father(X,Y):-male(X),(son(Y,X);(siblings(Y,Z),son(Z,X))).
daughter(X,Y):-female(X),son(Z,Y),siblings(X,Z).


Blogger Comments:


Emoticon Emoticon

Most read this week!