I have just completed passing some variables down to another method and matching them to facts. I now want to add some security in the form of an if statement. I am hoping to check to see the variable inputted by the user is valid (this is in the form of a number)
An example of this is shown in the code below, basically a user chooses an option between 1 and 10, if the user inputs an invalid option (ie 11) I want the method to print out "invalid choice" and repeat the method.
My question: How do I implement an if statement into Prolog code, the method before the code shown below would pass in a number
ifStatment(X) :-
write("Here is your list"),
nl,nl,
forall(listOfStuff(X,Text), writeln(Text)),
read(Y),
The title of the question
IF Statement in Prolog
uses the wordif
which to most programmers brings up the concept of an if statement. In terms of logic programming the wordif
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:
Note the use of
,
which meansand
in Prolog. This readsThe second clause guard statements are:
Note the use of
;
which meansor
in Prolog. This readsThe 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
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.Here is the complete code snippet. To change using either
valid_1
orvalid_2
just make one or the other a comment using%
.Here is a sample query.