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

2 answers

  • answered 2018-05-16 06:30 joel76

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

  • answered 2018-05-16 17:27 fferri

    Using between/3 and forall/2:

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