Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).
like image 618
dasen Avatar asked Oct 13 '10 18:10

dasen


1 Answers

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
?- 
like image 193
Jeff Dallien Avatar answered Nov 09 '22 23:11

Jeff Dallien