简体   繁体   中英

Prolog print numbers from 1 to N?

Assume the user gives an input N to the function, how would I print these numbers from 1 to N (recursively or other wise).

example

print_numbers(40).

->1
->2
->…
->40

You want to print numbers from 1 to N so print_numbers(N) can be translated in print_numbers(1, N).

Now what is print_numbers from X to Y ?

print_numbers from X to Y is print(X) and print_numbers from X+1 to N!

In Prolog, you will get :

print_numbers(N) :-
    print_numbers(1, N).

% general case X must be lower than Y
print_numbers(X, Y) :-
    X =< Y,
    writeln(X),
    X1 is X + 1,
    print_numbers(X1, Y).

Using between/3 and forall/2 :

?- forall(between(1, 40, X), writeln(X))
1
2
3
...
39
40
true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM