简体   繁体   中英

How to Print numbers from 1 to 100 in Prolog?

The following code is a Prolog code which gives all integers greater than 0. Each time i put ; in the interpreter, it gives the next number:

is_integer(0).
is_integer(X) :- is_integer(Y),X is Y+1.

Is there a way where it gives numbers between 0 and 100 only. When it reaches 100 it should stop.

There is a built-in predicate between/3 for that purpose in B, Ciao, SICStus (library), SWI, YAP, XSB (library).

?- between(0,100,X).
X = 0 ;
X = 1 ;
...
X = 100.

If you start to learn Prolog, better try to use s(X) numbers first which are much easier to understand and reason about. The same example, but only going up to 3:

?- nat_nat_sum(N,_,s(s(s(0)))).

with the definition:

nat_nat_sum(0,I,I).
nat_nat_sum(s(I),J,s(K)) :-
   nat_nat_sum(I,J,K).

What a nice quiz. It exemplifies very well how difficult can be to control the recursion with the minimal tools that Prolog defines. We must commit our solutions to values lower than the predefined limit, restricting the otherless unbound search:

is_integer(0).
is_integer(X) :-
    is_integer(Y),
    ( Y >= 100, ! ; X is Y + 1 ).

Here is the trace output limiting the range to 3 (ie ... Y >= 3, ! ; ... )

?- is_integer(X).
X = 0 ;
X = 1 ;
X = 2 ;
X = 3 ;
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