The title of the question IF Statement in Prolog
uses the word if
which to most programmers brings up the concept of an if statement. In terms of logic programming the word if
brings up the concept of the conditional ->/2 or predicates with guard statements. This answer demonstrates both ways on the same problem with the same result.
Extending from your previous question and the accepted answer.
The first way uses the predicate valid_1(N)
to check if the input is valid. This does not use ->/2
but uses a two clause predicate with mutually independent guard statements.
The first clause guard statements are:
(0 < N, N < 11)
Note the use of ,
which means and
in Prolog. This reads
N is greater than 0 AND N is less than 11.
The second clause guard statements are:
(N < 1; N > 10)
Note the use of ;
which means or
in Prolog. This reads
N is less than 1 OR N is greater than 10.
The second way uses the predicate valid_2(N)
to check if the input is valid. This uses ->/2.
The format for using the conditional is
(
% condition
->
% true
;
% false
)
these can be nested and that is done in this example.
Note: The use of the comments % condition
, % true
and % false
are not required. I added them for clarity.
valid_2(N) :-
(
% condition
0 < N
->
% true
(
% condition
N < 11
->
% true
writeln("Valid entry.")
;
% false
writeln("Invalid entry. Please try again.")
)
;
% false
writeln("Invalid entry. Please try again.")
).
Here is the complete code snippet.
To change using either valid_1
or valid_2
just make one or the other a comment using %
.
tell_me_your_problem:-
output_problems,
read_input.
output_problems :-
forall(problem(P),
writeln(P)).
read_input :-
repeat,
read_string(user_input, "\n", "\r\t ", _, Line),
process_input(Line).
process_input(Line) :-
string(Line),
atom_number(Line, N),
integer(N),
%valid_1(N),
valid_2(N),
do_something_with(Line),
fail.
process_input("quit") :-
write('Finished'), nl,
!, true.
valid_1(N) :-
(0 < N, N < 11),
writeln("Valid entry.").
valid_1(N) :-
(N < 1; N > 10),
writeln("Invalid entry. Please try again.").
valid_2(N) :-
(
% condition
0 < N
->
% true
(
% condition
N < 11
->
% true
writeln("Valid entry.")
;
% false
writeln("Invalid entry. Please try again.")
)
;
% false
writeln("Invalid entry. Please try again.")
).
do_something_with(X) :-
writeln(X).
problem('1').
problem('2').
problem('3').
problem('4').
problem('5').
problem('6').
problem('7').
problem('8').
problem('9').
problem('10').
Here is a sample query.
?- tell_me_your_problem.
1
2
3
4
5
6
7
8
9
10
|: 11
Invalid entry. Please try again.
11
|: 0
Invalid entry. Please try again.
0
|: 5
Valid entry.
5
|: quit
Finished
true .