问题
Hello i have a problem with if statement. i have this
final(C1-W1,C2-W2,C3-W3):-
retractall(end_jug),
asserta( end_jug(C1,W1) ),
asserta( end_jug(C2,W2) ),
asserta( end_jug(C3,W3) ).
and this one
katastasi(L) :-
findall(X-W, jug(X,W), L0), sort(L0,L).
How can i have this check????:
if(jug(C1,W1) == end_jug(C1,W1) && jug(C2,W2) == end_jug(C2,W2) && jug(C3,W3) == end_jug(C3,W3)) write('Congrats').
Thanks in advance!!
回答1:
Like this:
is_final_state :-
katastasi(S), writeln(S),
S=[C1-W1,C2-W2,C3-W3],
( end_jug(C1,W1),
end_jug(C2,W2),
end_jug(C3,W3)
-> writeln('Congrats!')
; W1+W2+W3 < 6
-> writeln('WARNING: not enough water left!'),
fail
).
You should've mentioned your previous question. This code is a part of the code in the answer there.
Your code is in Prolog, but the check you asked about was in "Basic". Let go of the Basic mentality. :) Prolog does the checks for you, as part of unification.
The value 6
in the code above should be calculated really, according to the final values the user specifies by calling final
at the start fo the game. The final value (of each end_jug
fact) can be retrieved just like the current value (of each jug
fact) is retrieved by jugsState
predicate (which I assume is now called katastasi
).
Now you must complete your game by writing the stop
predicate, which should do the cleanup (i.e. call retract
on all the asserted facts). You can even make an undo
predicate. :)
回答2:
Just write the conditions joined by ,
under a new predicate:
win(C1, W1, C2, W2, C3, W3):-
jug(C1,W1) \== end_jug(C1,W1),
jug(C2,W2) \== end_jug(C2,W2),
jug(C3,W3) \== end_jug(C3,W3).
Then use this predicate when needed.
finish(C1, W1, C2, W2, C3, W3):-
win(C1, W1, C2, W2, C3, W3),
write('Congrats').
Or write it as a whole:
finish(C1, W1, C2, W2, C3, W3):-
jug(C1,W1) \== end_jug(C1,W1),
jug(C2,W2) \== end_jug(C2,W2),
jug(C3,W3) \== end_jug(C3,W3),
write('Congrats').
来源:https://stackoverflow.com/questions/9420073/if-statement-in-prolog