How would you code a program in Prolog to print numbers from 1 to 10 using recursion?
How would you code a program in Prolog to print numbers from 1 to 10 using recursion?
I've tried the following but it doesn't work, can you tell me why?
print_numbers(10) :- write(10).
print_numbers(X) :- write(X),开发者_如何学编程nl,X is X + 1, print_numbers(X).
Your code is very close to working. The problem is that you cannot reuse X, once it is instantiated, it cannot be changed (see here for more details). Use a new variable, like this:
print_numbers(10) :- write(10), !.
print_numbers(X) :- write(X), nl, Next is X + 1, print_numbers(Next).
Adding the cut (!) to the end will prevent the interpreter from asking if you want to see more results.
?- print_numbers(1).
1
2
3
4
5
6
7
8
9
10
Yes
?-
print_from_1_to_10 :-
print_from_X_to_10(1).
print_from_X_to_10(X) :-
(
X > 10
->
fail
;
writeln(X),
NewX is X + 1,
print_from_X_to_10(NewX)
).
Been a seriously long time since I wrote any prolog but I'd probably do things just a little differently. Something like this, though I can't test it at the momment.
print_increasing_numbers(From, To):- From > To, !, write('ERROR: From > To').
print_increasing_numbers(To, To):- !, write(To).
print_increasing_numbers(From, To):- write(From),
nl,
Next is From + 1,
print_increasing_numbers(Next, To).
A key difference here is the !
, or cut operation, which stops backtracking. If you don't include it then you will get a solution with the first clause when X
is 10,but if you ask for a second solution it will backtrack and match the second clause as well. That would result in a much larger list of numbers than you want.
Just call defineXandY from terminal
defineXandY :-
print_one_to_ten(1,10).
print_one_to_ten(X,Y) :-
X<Y,
write(X),nl,
NewX is X+1,
print_one_to_ten(NewX,Y).
精彩评论