How would you encode a program in Prolog to print numbers from 1 to 10 using recursion?

How would you encode a program in Prolog to print numbers from 1 to 10 using recursion?

I tried the following, but it does not work, can you tell me why?

print_numbers(10) :- write(10). print_numbers(X) :- write(X),nl,X is X + 1, print_numbers(X). 
+6
recursion prolog
source share
3 answers

Your code is very close to work. The problem is that you cannot reuse X, once it is created, it cannot be changed (see here for more information). Use a new variable, for example:

 print_numbers(10) :- write(10), !. print_numbers(X) :- write(X), nl, Next is X + 1, print_numbers(Next). 

Adding an abbreviation (!) To the end will not allow the interpreter to ask if you want to see more results.

 ?- print_numbers(1). 1 2 3 4 5 6 7 8 9 10 Yes ?- 
+9
source share

For a long time, seriously , since I wrote a prologue, but I will probably do something completely different. Something like this, although I can't check it for a moment.

 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). 

The key difference here is the operation ! or a cut that stops the rollback. If you do not include it, you will get a solution with the first sentence, when X is 10, but if you ask for a second solution, it will return and will correspond to the second sentence. This will lead to a much larger list of numbers than you want.

0
source share
 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) ). 
0
source share

All Articles