Prolog Conditional
Prolog Conditional
2
Prolog Conditional
Related to the !, is the Prolog conditional test:
(Test -> ThenC ; ElseC)
where each of Test, ThenC, ElseC can be a general Prolog
query.
3
Conditional Example
student_fees(S, F):-
student(S),
(eu(S)->F=13500; F=29500).
The Effect of the
Prolog Conditional
Ignoring variables, given
H :- ., (Test -> ThenC ; ElseC),
its effectis equivalent to rewriting the clause
as:
H:- , cond,.
Where cond is defined as:
cond :- Test, !, ThenC.
cond :- ElseC.
Some Prologs implement it this way.
4
student_fees(S, F):-
student(S), (eu(S)->F=13500; F=29500).
This can be written alternatively as:
student_fees(S, F):-
student(S), check_fees(S,F).
check_fees(S, F) :-
eu(S), !, F=13500.
check_fees(S, F) :- F=29500.
5
6
Conditional Examples
weekend_plan(D, P):-
(dry_forecast(D),
+transport_strike(D),
country-park(Park)) ->
P=goto(Park);
(film(F), P=goto(cinema(F))).
7
dry_forecast(16).dry_forecast(23).
country_park(richmond). transport_strike(23).
country_park(petworth). film(batman).
film(superman).
weekend_plan(D, P):-
(dry_forecast(D),
+transport_strike(D),
country-park(Park)) ->
P=goto(Park);
(film(F), P=goto(cinema(F))).
8
?- weekend_plan(16, P).
P= goto(richmond) ;
no.
?- weekend_plan(23, P).
P=goto(cinema(batman));
P=goto(cinema(superman));
no.
9
Compare With
dry_forecast(16).dry_forecast(23).
country_park(richmond). transport_strike(23).
country_park(petworth). film(batman).
film(superman).
alt_weekend_plan(D, P):-
(dry_forecast(D),
+transport_strike(D)) ->
(country-park(Park), P=goto(Park));
(film(F), P=goto(cinema(F))).
?- alt_weekend_plan(16, P).
P = goto(richmond);
P = goto(petworth);
no
?- alt_weekend_plan(23, P).
P = goto(cinema(batman));
P = goto(cinema(superman));
no
10
Yet another definition of max
alt_max(X,Y, Z) :- Y>X -> Z=Y; Z=X.
?- alt_max(1, 2, X).
X=2
?- alt_max(1, 2, 1).
no
11
Reviews
There are no reviews yet.