Generate range ints - "from local stack" [beginner]

gen(N,R)

:

R

is a value from 0 to N-1 in order. N

non-zero positive int. N

always indicated.

For example: ?- genN(2,R)

. gives R=0;R=1.

I implemented like this, but it has "from local static error":

gen(X,0).
gen(X,R) :-
  gen(X,R1),
  R is R1+1,
  R<X,       % why this line
  R>=0.      % and this line can't keep the range successfully?

      

Result:

 ?- genN2(3,R).  
    R = 0 ;
    R = 1 ;
    R = 2 ;
    ERROR: Out of local stack

      

+3


source to share


1 answer


Use failure-slice to understand why your program does not terminate . To that end, we'll add a few additional goals to help you understand why the goals you've added don't matter. If this resulting snippet does not terminate, your original program will not terminate either. As you can see, there isn't much in this part. In fact, your program will never terminate . false

gen (_X, 0): - false .
gen (X, R): -
  gen (X, R1), false ,
   R is R1 + 1 ,
   R <X ,
   R> = 0 .

(There are a few more problems: your definition will be correct for a goal such as gen(-1,0)

, which is probably not what you intended.)



The best way to solve this problem right away is to use instead of a more complicated one to handle, (is)/2

or just use between/3

:

gen(N0, R) :-
   N1 is N0-1,
   between(0, N1, R).

      

+3


source







All Articles