I am a writing Prolog predicate that would compare some point (myPosition(2,2)) in Cartesian coordinate system with some other point in the neighbourhood. As a result, it should show the direction (north, east, south, west) that we should choose to get from myPosition(2,2) to that point. Here is the code of my .pl file:
myPosition(2,2).
turn_to_east(X+1,Y) :-
myPosition(X,Y),
write('East.').
turn_to_west(X-1,Y) :-
myPosition(X,Y),
write('West.').
turn_to_north(X,Y+1) :-
myPosition(X,Y),
write('North.').
turn_to_south(X,Y-1) :-
myPosition(X,Y),
write('South.').
turn_to_the_point(X,Y) :- turn_to_east(X,Y).
turn_to_the_point(X,Y) :- turn_to_west(X,Y).
turn_to_the_point(X,Y) :- turn_to_north(X,Y).
turn_to_the_point(X,Y) :- turn_to_south(X,Y).
Then, when I upload the file to SWI-Prolog and write:
turn_to_the_point(1,2).
I get just:
false.
Why can't I get the answer 'West.' or any other?
The reason is that by default Prolog does not interpret +, - and other arithmetic operators. 1+1 is simply 1+1 (this is syntactical sugar for +(1,1)), not 2. This could be useful if you for instance would like to define your own expression evaluator, and you see + as the boolean sum, or something completely different.
There is however one way to collapse such expression such that it derives 2 out of 1+1 using the (is)/2 predicate. For instance:
turn_to_east(NX,Y) :-
myPosition(X,Y),
NX is X+1,
write('East.').
Given you query turn_to_east/2 with turn_to_east(1,2), NX = 1. Now you fetch the myPosition/2 data: X = 2 and Y = 2. Prolog does an equivalence check in the meantime and sees that the Y-coordinate of turn_to_east/2 is the same as the one of myPosition. Next it collapses 2+1 to 3 and sees that this is not equivalent to NX = 1 so this predicate fails. But if you had queried turn_to_east(3,1) it would have succeeded and thus write East..
If you modify your entire theory with the above discussed concept, like:
myPosition(2,2).
turn_to_east(NX,Y) :-
myPosition(X,Y),
NX is X+1,
write('East.').
turn_to_west(NX,Y) :-
myPosition(X,Y),
NX is X-1,
write('West.').
turn_to_north(X,NY) :-
myPosition(X,Y),
NY is Y+1,
write('North.').
turn_to_south(X,NY) :-
myPosition(X,Y),
NY is Y-1,
write('South.').
turn_to_the_point(X,Y) :- turn_to_east(X,Y).
turn_to_the_point(X,Y) :- turn_to_west(X,Y).
turn_to_the_point(X,Y) :- turn_to_north(X,Y).
turn_to_the_point(X,Y) :- turn_to_south(X,Y).
It answers the query correctly:
?- turn_to_the_point(1,2).
West.
true ;
false.
A note in general is that predicates better not have side-effects like write/1 stuff: this is not only for Prolog, almost all programming languages advice to split a program into calculation and interaction. Perhaps a better way to solve this, is to see the direction as an parameter:
myPosition(2,2).
turn_to_point(NX,Y,east) :-
myPosition(X,Y),
NX is X+1.
turn_to_point(NX,Y,west) :-
myPosition(X,Y),
NX is X-1.
turn_to_point(X,NY,north) :-
myPosition(X,Y),
NY is Y+1.
turn_to_point(X,NY,south) :-
myPosition(X,Y),
NY is Y-1.
turn_to_the_point(X,Y) :-
turn_to_point(X,Y,D),
write(D).
In that case the turn_to_the_point/2 predicate is clearly an interaction predicate whereas its turn_to_the_point/3 variant does computations.
Related
I have an add2 predicate which resolves like this where s(0) is the successor of 0 i.e 1
?- add2(s(0)+s(s(0)), s(s(0)), Z).
Z = s(s(s(s(s(0)))))
?- add2(0, s(0)+s(s(0)), Z).
Z = s(s(s(0)))
?- add2(s(s(0)), s(0)+s(s(0)), Z).
Z = s(s(s(s(s(0)))))
etc..
I'm trying to do add in a predecessor predicate which will work like so
?- add2(p(s(0)), s(s(0)), Z).
Z = s(s(0))
?- add2(0, s(p(0)), Z).
Z = 0
?- add2(p(0)+s(s(0)),s(s(0)),Z).
Z = s(s(s(0)))
?- add2(p(0), p(0)+s(p(0)), Z).
Z = p(p(0))
I can't seem to find a way to do this. My code is below.
numeral(0).
numeral(s(X)) :- numeral(X).
numeral(X+Y) :- numeral(X), numeral(Y).
numeral(p(X)) :- numeral(X).
add(0,X,X).
add(s(X),Y,s(Z)) :- add(X,Y,Z).
add(p(X),Y,p(Z)) :- add(X,Y,Z).
resolve(0,0).
resolve(s(X),s(Y)) :-
resolve(X,Y).
resolve(p(X),p(Y)) :-
resolve(X,Y).
resolve(X+Y,Z) :-
resolve(X,RX),
resolve(Y,RY),
add(RX,RY,Z).
add2(A,B,C) :-
resolve(A,RA),
resolve(B,RB),
add(RA,RB,C).
In general, adding with successor arithmetic means handling successor terms, which have the shape 0 or s(X) where X is also a successor term. This is addressed completely by this part of your code:
add(0,X,X).
add(s(X),Y,s(Z)) :- add(X,Y,Z).
Now you have to make a decision; you can either handle the predecessors and the addition terms here, in add/3, or you can wrap this predicate in another one that will handle them. You appear to have chosen to wrap add/3 with add2/3. In that case, you will definitely need to create a reducing term, such as you've built here with resolve/2, and I agree with your implementation of part of it:
resolve(0,0).
resolve(s(X),s(Y)) :-
resolve(X,Y).
resolve(X+Y,Z) :-
resolve(X,RX),
resolve(Y,RY),
add(RX,RY,Z).
This is all good. What you're missing now is a way to handle p(X) terms. The right way to do this is to notice that you already have a way of deducting by one, by using add/3 with s(0):
resolve(p(X), R) :-
resolve(X, X1),
add(s(0), R, X1).
In other words, instead of computing X using X = Y - 1, we are computing X using X + 1 = Y.
Provided your inputs are never negative, your add2/3 predicate will now work.
sibling(X, Y):- father(Z, X), father(Z, Y), not (X=Y).
sister(X, Y):- father(Z, X), father(Z, Y), female(X).
brother(X, Y):- father(Z, X), father(Z, Y), male(X).
i'm having a bit problem with using the not function. i've tried not X=Y. but to no avail, the sibling rule still produce error.
if i were to delete the not x=y, the output will be a bit kind of "ugly".
how should i write the not function?
The ISO predicate implementing not provable is called (\+)/1.
However, as #coder explains in the comments, it is much better to use dif/2 to express that two terms are different.
dif/2 is a pure predicate that works correctly in all directions, also if its arguments are not yet instantiated.
For example, with (\+)/1, we get:
?- \+ (X = Y ).
false.
No X and Y exist that satisfy this goal, right? Wrong:
?- X = a, Y = b, \+ (X = Y ).
X = a,
Y = b.
In contrast, with dif/2:
?- dif(X, Y).
dif(X, Y).
and in particular:
?- X = a, Y = b, dif(X, Y).
X = a,
Y = b.
See prolog-dif for more information. dif/2 is with us since the very first Prolog system. I strongly recommend you use it.
SWI Prolog has no notoperator. it can be used as a regular compound term, e.i. not(X).
It must be no space between functor and open parenthesis:
foo( argument list ).
This is the cause of the error.
SWI Prolog suggests ISO-standard replacement for not/1: (\+)/1
I am doing Prolog Programming for my research and I got some problems..
First, all of my codes are below.
%% Lines are without period(.)
diagnosis :-
readln(Line1),
readln(Line2),
readln(Line3),
readln(Line4),
readln(Line5),
readln(Line6),
readln(Line7),
readln(Line8),
readln(Line9),
readln(Line10),
write(Line1),nl,
write(Line2),nl,
write(Line3),nl,
write(Line4),nl,
write(Line5),nl,
write(Line6),nl,
write(Line7),nl,
write(Line8),nl,
write(Line9),nl,
write(Line10),nl.
%% (get_symptom(Line1,[man]) -> write('man!!!!!!!!!')),
%% (get_symptom(Line2,[woman]) -> write('woman!!!!!!!!!')).
%% if A then B else C, (A->B; C)
%% grammar
s --> np, vp.
np --> det, n.
vp --> v, np.
det --> [a].
n --> [man].
v --> [has].
n --> [woman].
n --> [fever].
n --> [runny_nose].
get_symptom(Line,N) :- s(Line,[]), member(N,Line).
member(X, [X|T]).
member(X,[H|T]) :-
member(X,T).
%% FindSymptom(Line, [Symptom]) : - s(Line,[]), np(_, _, object,[a,
%% Symptom]), n(singular, [Symptom], []).
start :-
write('What is the patient''s name? '),
readln(Patient), %% Here, this can be used for input of all symtoms
diagnosis,
hypothesis(Patient,cold,S1),
append([cold/S1/red],[],N1), write(S1),
write('until...'),
hypothesis(Patient,severe_cold,S2), write(S2),
append([severe_cold/S2/red],N1,BarList),
write('until...'),
%% write(Patient,"probably has ",Disease,"."),nl.
hypothesis(Patient,Disease,100),
write(Patient),
write(' probably has '),
write(Disease),
write('.'),
test_barchart(BarList).
start :-
write('Sorry, I don''t seem to be able to'),nl,
write('diagnose the disease.'),nl.
symptom(Patient,fever) :-
get_symptom(Line1, [fever]);
get_symptom(Line2, [fever]);
get_symptom(Line3, [fever]);
get_symptom(Line4, [fever]);
get_symptom(Line5, [fever]);
get_symptom(Line6, [fever]);
get_symptom(Line7, [fever]);
get_symptom(Line8, [fever]);
get_symptom(Line9, [fever]);
get_symptom(Line10, [fever]).
symptom(Patient,runny_nose) :-
get_symptom(Line1, [runny_nose]);
get_symptom(Line2, [runny_nose]);
get_symptom(Line3, [runny_nose]);
get_symptom(Line4, [runny_nose]);
get_symptom(Line5, [runny_nose]);
get_symptom(Line6, [runny_nose]);
get_symptom(Line7, [runny_nose]);
get_symptom(Line8, [runny_nose]);
get_symptom(Line9, [runny_nose]);
get_symptom(Line10, [runny_nose]).
hypothesis(Patient,cold,Score_Cold) :-
(symptom(Patient,fever), Score_Cold is 100),write('!!!');
Score_Cold is 0.
hypothesis(Patient,severe_cold,Score_Severe) :-
((symptom(Patient,fever), Score1 is 50);
Score1 is 0),
((symptom(Patient, runny_nose), Score2 is 50);
Score2 is 0),
Score_Severe is Score1 + Score2.
%% hypothesis(Disease) :-
%%(hypothesis1(Patient,cold,Score1),
%%Score1 =:= 100 -> Disease = cold);
%%(hypothesis2(Patient,severe_cold,Score2),
%%Score2 =:= 100 -> Disease = severe_cold).
%% make graph for the result
:- use_module(library(pce)).
:- use_module(library(plot/barchart)).
:- use_module(library(autowin)).
test_barchart(BarList):-
new(W, picture),
send(W, display, new(BC, bar_chart(vertical,0,100))),
forall(member(Name/Height/Color,
BarList),
( new(B, bar(Name, Height)),
send(B, colour(Color)),
send(BC, append, B)
)),
send(W, open).
%% [X/100/red, y/150/green, z/80/blue, v/50/yellow]
%% append List
append([], L, L).
append([H|T], L2, [H|L3]):-
append(T, L2, L3).
As you can see, I want to make a bar_graph from 10 input lines by extracting symptoms..
But when I executed this code, I got the result as below...
1 ?- start.
What is the patient's name? GJ
|: a man has a runny_nose
|: a
|: a
|: a
|: a
|: a
|: a
|: a
|: a
|: a
[a,man,has,a,runny_nose]
[a]
[a]
[a]
[a]
[a]
[a]
[a]
[a]
[a]
!!!100until...100until...!!![GJ] probably has cold.
true
I only typed one symptom (runny_nose). I want to get Score for "cold" is 0, Score for "severe_cold" is 50 and BarGraph result... But What Happened? I can't find..
*****Edited******
I found that the problem is related to local variables (Line1, .. ,Line10) But how can I deal with? If I can make all the variables; Line1, ... , Line10 as global variables then, I think the problem can be solved...
****Addition*****
I changed my 'start' predicate as follows...I didn't use 'diagnosis' and 'hypothesis' predicates/ But the problems is maybe.. 'get_symptoms' predicate. Is there any choice I can choose except that I don't use 'get_symptoms' and 'symptoms' predicates...? Then the code will become very coarse...
start :-
write('What is the patient''s name? '),
readln(Patient), %% Here, this can be used for input of all symtom
readln(Line1),
readln(Line2),
readln(Line3),
readln(Line4),
readln(Line5),
readln(Line6),
readln(Line7),
readln(Line8),
readln(Line9),
readln(Line10),
(symptom(Patient,fever,Line1,Line2,Line3,Line4,Line5,Line6,Line7,Line8,Line9,Line10) -> (Cold is 80, Severe_Cold is 50)),
(symptom(Patient,runny_nose,Line1,Line2,Line3,Line4,Line5,Line6,Line7,Line8,Line9,Line10) -> Severe_Cold is Severe_Cold + 50),
write(Severe_Cold), write(Cold),
append([cold/Cold/red],[],N1),
append([severe_cold/Severe_Cold/red],N1,BarList),
%% write(Patient,"probably has ",Disease,"."),nl.
write(Severe_Cold),
((Cold =:= 100 -> Disease = cold) ; (Severe_Cold =:= 100 -> Disease = severe_cold)),
write(Patient),
write(' probably has '),
write(Disease),
write('.'),
test_barchart(BarList).
When programming in Prolog, you need to do some research into the language to understand how it works. Many Prolog beginners make the mistake of learning a couple of snippets of Prolog logic and then apply what they know of other languages to attempt to create a valid Prolog programming. However, Prolog doesn't work like other common languages at all.
Regarding variables, there are no globals. Variables are always "local" to a predicate clause. A predicate clause is one of one or more clauses that describe a predicate. For example:
foo(X, Y) :- (some logic including X and Y).
foo(X, Y) :- (some other logic including X and Y).
foo(X, X) :- (some other logic including X).
These are three clauses describing the predicate foo/2. The value of X or Y instantiated in one clause isn't visible to the other clauses.
If you want to instantiate a variable in one predicate and use it in another, you have to pass it as a parameter:
foo([1,2,3,4], L),
bar(L, X).
Here, foo might instantiate L using some logic and based upon the instantiated value of [1,2,3,4] for the first argument. Then L (now instantiated) is passed as the first argument to the predicate bar.
If you need a value to be persistent as data, you could assert it as a fact as follows:
foo :-
(some logic that determines X),
assertz(my_fact(X)),
(more logic).
bar :-
my_fact(X), % Will instantiate X with what was asserted
(some logic using X).
This would work, but is not a desirable approach in Prolog to "fake" global variables. Asserting items into persistent data is designed for the purpose of maintaining a Prolog database of information.
So you can see that the logic you have involving Line1, Line2, ... will not work. One clue would be that you must have received many warnings about these variables being "singleton". You need to study Prolog a bit more, then recast your logic using that knowledge.
It's been a while since I've programmed in Prolog. Today, I tried to make a simple program. It lists some facts of who belongs to the same family. If two people belong to the same family, they cannot give eachother gifts. I want to get all the people (or at least one person) to whom someone is allowed to give a gift.
family(john, jack).
family(matt, ann).
family(ann, jack).
family(jordan, michael).
family(michael, liz).
sameFamily(X, Y) :-
family(X, Y).
sameFamily(X, X) :-
false.
sameFamilySym(X, Y) :-
sameFamily(X, Y).
sameFamilySym(X, Y) :-
sameFamily(Y, X).
sameFamilyTrans(X, Z) :-
sameFamilySym(X, Y),
sameFamilySym(Y, Z).
gift(X, Y) :-
not(sameFamilyTrans(X, Y)).
Some queries if sameFamilyTrans/2 return false when they should in fact return true.
sameFamilyTrans/2 is obviously wrong. I think I need to keep a list of intermediate transitivities. Something like this:
sameFamilyTrans(X, Z, [Y|Ys]) :-
sameFamilySym(X, Y, []),
sameFamilyTrans(Y, Z, Ys).
But then I don't know how to call this.
P.S. I am using SWI-Prolog, if that makes any difference.
Yes, you were on the right track. The trick is to call the transitive closure with an empty accumulator, and check in each step whether a cycle is found (i.e., whether we have seen this member of the family before. As "false" has pointed out, the persons need to be instantiated already before going into the not, though.
So in sum, this works:
family(john, jack).
family(matt, ann).
family(ann, jack).
family(jordan, michael).
family(michael, liz).
sameFamily(X, Y) :-
family(X, Y).
sameFamilySym(X, Y) :-
sameFamily(X, Y).
sameFamilySym(X, Y) :-
sameFamily(Y, X).
sameFamilyTrans(X, Y, Acc) :-
sameFamilySym(X, Y),
not(member(Y,Acc)).
sameFamilyTrans(X, Z, Acc) :-
sameFamilySym(X, Y),
not(member(Y,Acc)),
sameFamilyTrans(Y, Z, [X|Acc]).
person(X) :- family(X, _).
person(X) :- family(_, X).
gift(X, Y) :-
person(X),
person(Y),
X \= Y,
not(sameFamilyTrans(X, Y, [])).
A bit of background: Transitive closure is not actually first-order definable (cf. https://en.wikipedia.org/wiki/Transitive_closure#In_logic_and_computational_complexity). So it can be expected that this would be a little tricky.
Negation is implemented in Prolog in a very rudimentary manner. You can essentially get a useful answer only if a negated query is sufficiently instantiated. To do this, define a relation person/1 that describes all persons you are considering. Then you can write:
gift(X,Y) :-
person(X),
person(Y),
\+ sameFamily(X,Y).
There is another issue with the definition of sameFamily/2.
This is the problem :
Victor has been murdered, and Arthur, Bertram, and Carleton are
suspects. Arthur says he did not do it. He says that Bertram was the
victim’s friend but that Carleton hated the victim. Bertram says he
was out of town the day of the murder, and besides he didn’t even know
the guy. Carleton says he is innocent and he saw Arthur and Bertram
with the victim just before the murder. Assuming that everyone–except
possibly for the murderer–is telling the truth, use resolution to
solve the crime.
This is what I wrote in SWI Prolog
% Facts:
p('Arthur'). % suspect
p('Bertram'). % suspect
p('Carleton'). % suspect
p('Victor'). % victim
% Arthur
says('Arthur', i('Arthur')).
says('Arthur', f('Bertram', 'Victor')).
says('Arthur', ht('Carleton', 'Victor')).
% Bertram
says('Bertram', o('Bertram')).
says('Bertram', nk('Bertram', 'Victor')).
% Carleton
says('Carleton', i('Carleton')).
says('Carleton', t('Arthur', 'Victor')).
says('Carleton', t('Bertram', 'Victor')).
% Rules:
holds(X) :- says(Y, X), \+m(Y).
holds(i(X)) :- p(X), \+m(X).
holds(f(X,Y)) :- p(X), p(Y), holds(f(Y,X)).
holds(f(X,Y)) :- p(X), p(Y), \+holds(nk(X,Y)).
holds(o(X)) :- p(X), p(Y), holds(t(X,Y)).
holds(o(X)) :- p(X), \+m(X).
holds(nk(X,Y)) :- p(X), p(Y), \+holds(nk(Y,X)).
holds(nk(X,Y)) :- p(X), p(Y), \+holds(f(X,Y)).
holds(t(X,Y)) :- p(X), p(Y), holds(t(Y,X)).
holds(t(X,Y)) :- p(X), p(Y), p(Z), holds(t(X,Z)), holds(t(Z,Y)).
m(X) :- p(X).
The answer is suppose to be Bertram, but I kept on getting Arthur. Dont know what am I doing wrong.
I'm fairly sure that Rules will be far more simpler than that.
For instance, what does mean m(X) :- p(X)., given that p(X) is always true ? Does Victor have something to say ?
In logic it's essential to stick to Occam's Razor. Programming logic it's not an exception, albeit the term has a more practical connotation - see KISS principle.
I think we can only agree that the murder should be the person that contradicts other two. There is only a fact in question: whether or not a person known Victor.
Then what we know about the crime can be summarized:
t(a) :- k(b), k(c).
t(b) :- \+ k(b).
t(c) :- k(a), k(b).
k(_).
where t(X) stands for X testimony that, and k(X) stands for X known Victor.
We don't really know about k(X), then we must add k(_).
With that, Prolog can suggest:
?- t(X).
X = a ;
X = c.
I.e. only a or b can be true.
EDIT: because Prolog isn't propositive when it came to negation, here is a way to solicit the solution:
m(X) :- member(X, [a,b,c]), \+ t(X).
But let's take a more explicit approach:
Instead of clausal form, that leads to immediate availability of Prolog execution, as shown above, our fact base could also expressed:
say(a, know_victim(b, yes)).
say(a, know_victim(c, yes)).
say(b, know_victim(b, no)).
say(c, know_victim(a, yes)).
say(c, know_victim(b, yes)).
now let's see if some some individual says the opposite of others
liar(I) :-
select(I, [a,b,c], Js),
say(I, Fact),
maplist(negate(Fact), Js).
negate(know_victim(I, X), J) :-
say(J, know_victim(I, Y)),
X \= Y.
yields
?- liar(I).
I = b ;
false.
https://github.com/Anniepoo/prolog-examples
contains several different ways of solving this.