Reputation: 69
I want to translate my natural code in prolog
.
Here is my natural code :
if E < W then
if C < Max then
print('increment C')
else
print('C unchanging')
if E > W then
if C > Min then
print('decrement C')
else
print('error')
Here is my code in SWI-Prolog :
tddv_worst(_).
tddv_best(_).
tddv_courant(_).
tddv_estime(_).
etendue_gisement_courant(_).
etendue_gisement_min(_).
etendue_gisement_max(_).
compromis_1(tddv_estime(E),tddv_worst(W),etendue_gisement_courant(C),etendue_gisement_min(Min),etendue_gisement_max(Max)) :-
(E < W , C < Max) -> writeln('Increment C') ; writeln('C unchanging') ;
(E > W , C > Min) -> writeln('Decrement C') ; writeln('Error').
When I write this in the interpreter :
compromis_1(tddv_estime(19),tddv_worst(16),etendue_gisement_courant(2),etendu e_gisement_max(8),etendue_gisement_min(1)).
It displays C unchanging
.
It's not supposed to display this.
Can someone explain me why ?
Upvotes: 1
Views: 68
Reputation: 58244
Your implementation isn't really equivalent to the C version you are showing.
Here's your current code:
(E < W , C < Max) -> writeln('Increment C') ;
writeln('C unchanging') ;
(E > W , C > Min) -> writeln('Decrement C') ;
writeln('Error').
Prolog sees this as a series of four clauses related by a logical disjunction (OR -- ;
). If the first ->
expression fails, it then calls the next disjunctive expression, writeln('C unchanging')
. The above code is roughly equivalent to:
if E < W and C < Max then
print('increment C')
else
print('C unchanging')
if E > W and C > Min then
print('decrement C')
else
print('error')
A Prolog equivalent of your original pseudo-code would be:
( E < W
-> ( C < Max
-> writeln('increment C')
; writeln('C unchanging')
)
) ;
( E > W
-> ( C > Min
-> writeln('decrement C')
; writeln('Error')
)
)
In Prolog, this behavior happens to work like the pseudo-code since ->
eliminates the choice point if it succeeds and Prolog will not backtrack.
Upvotes: 1