Tag: Prolog
Example Code #4 – Intersect and Write in Prolog
by Samet Kilictas on Jan.01, 2009, under Programming, Prolog
1- “!” character stops the query when it is false and “;” runs as “or” so it skips the false part then moves next part
smaller(X,Y):- X
X>Y,write(Y),write(' is bigger then '),write(X),!;
write('They are equal').
Query -> ?smaller(3,5) : 3 is smaller then 5
Query -> ?smaller(8,5) : 8 is bigger then 5
Query -> ?smaller(5,5) : They are equal
2- Intersect relation
Intersect function uses an external function inside. Member function checks whether the first parameter is member of the given list or not.
Query -> member(3,[3,4,5]).
member(HM,[HM|TM]).
member(XM,[HM|TM]):- member(XM,TM).
and the intersect function gives you the result on LI variable. Try it.
intersect([ ],LI,[ ]).
intersect([HI|TI],LI,LI2):- member(HI,LI),intersect(TI,LI,LI3),LI2=[HI|LI3],!;intersect(TI,LI,LI2).
Query -> intersect([3,4],LI,[4,5]) : [4]
Example Code #3 – Basics in Prolog
by Samet Kilictas on Dec.28, 2008, under Programming, Prolog
1- Parent relation between rex, doggie and goldie
dog(rex).
dog(X):-parent(X,Y).
parent(goldie,rex).
parent(jack,rex).
Query -> ?dog(goldie) : YES
Query -> ?dog(jack) : YES
2- Sister relation
sister(X,Y):-girl(X),girl(Y),parent(X,Z),parent(Y,Z).
parent(sara,Maria).
parent(lili,Maria).
girl(lili).
girl(maria).
Query -> ?sister(lili,maria) : NO
3- Finds factorial of numbers
1!: 1 , 2!: 2×1, 3!: 3×2x1
Here you can see that we are able to say 3!: 3×2! instead of 3!:3×2x1 . Since i know what is 1! and 0! therefore i have limitation points for my program.
fact(0,1):-!.
fact(1,1):-!.
fact(N,F,F1) :- N1 is N-1, fact(N1,F1), F is N * F1.
Thanks for dropping by! Feel free to join the discussion by leaving comments, and stay updated by subscribing to the 