Archive

Archive for the ‘Prolog’ Category

Example Code #4 – Intersect and Write in Prolog

January 1st, 2009 1 comment

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]

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Example Code #3 – Basics in Prolog

December 28th, 2008 No comments

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!: 3x2x1
Here you can see that we are able to say 3!: 3×2! instead of 3!:3x2x1 . 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.

Read more…

VN:F [1.9.22_1171]
Rating: 7.0/10 (3 votes cast)
VN:F [1.9.22_1171]
Rating: -1 (from 1 vote)