I am trying to count from 0 to N, one value returned at a time, rather than a list like with numlist/3. I believe it is possible to use recursion with two predicate statements, but I have gotten caught up on coming up with a stop condition which works in the manner I am looking for:
iterate(0,_).
iterate(X,N) :- iterate(Y,N), Y < N, X is Y + 1.
With my current understanding, the first predicate will always return 0 as the first value when calling iterate(X,N), and the second will iterate through recursive calls giving the next value.
The issue I have run into is that it correctly counts up to N, but then reaches the stack limit. I think that this is due to making the recursive call at the beginning of the predicate and checking on the return result afterwards.
The main disconnect seems to be my understanding of how Prolog deals with predicates. From what I have read, it seemed that Prolog handles the second call as follows:
iterate(Y,N) ⋀ (Y < N) ⋀ (X is Y + 1)
I thought that this would mean that when Y < N returns false, the recursive call would stop, which is not the case. At this point, I have tried a couple variations of the recursive call location in the predicate, always with the final value of X being declared at the end as it seems like that's where the value declaration must go.
I have also seen that ISO-Prolog has (;)/2 (if-then-else), but have not found anything similar which may be helpful in SWI-Prolog that could apply to this case.
Am I wrong in thinking that this is possible to do this with two predicate statements in SWI-Prolog?
Edit: I intend on doing this without an accumulator for added challenge.
;
is not the if-then-else but the "OR". The "if-then-else" is the->
– David Tonhofer;
is "OR", but in ISO-Prolog it is the "if-then-else" statement. Thank you for directing me to the->
operator in SWI, it helped me solve my problem! – TheWubMunzta