Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Print numbers from 1 to 100 in Prolog?

Tags:

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.

like image 415
user866821 Avatar asked Nov 28 '11 04:11

user866821


People also ask

How do you print an integer in Prolog?

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). Nice answer, although this fails after printing the numbers, which makes it difficult to use.

How do you print in Prolog?

o “print(x),print(y).” : The 'print' operator allows to use two 'print' predicate together, in this case, we can write the two print predicate together, if we input the value “print(x), print(y).” then it will combine variables from both together as 'xy'. For example: Input: “print(x),print(y).”

How do you increment numbers in Prolog?

Here's how to increment in Prolog: incr(X, X1) :- X1 is X+1. Note that two variables are needed: one to hold the original value and one for the incremented value. To do anything useful with the computation that this predicate performs, both variables have to be arguments of the predicate.

How do you count the number of elements in a list in Prolog?

We can simply use an if-then-else statement that either increments N is N1+1 , or sets N = N1 , like: count([],0). count([H|Tail], N) :- count(Tail, N1), ( number(H) -> N is N1 + 1 ; N = N1 ).


2 Answers

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).
like image 132
false Avatar answered Oct 03 '22 21:10

false


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 (i.e. ... Y >= 3, ! ; ...)

?- is_integer(X).
X = 0 ;
X = 1 ;
X = 2 ;
X = 3 ;
true.
like image 43
CapelliC Avatar answered Oct 03 '22 20:10

CapelliC