Home > Software design >  how iterate on an empty input in prolog?
how iterate on an empty input in prolog?

Time:09-03

i want to know if there are any methods to achieve an iteration in Prolog passing an empty input. For example I would like to have 0 on the first iteration, 1 on the next one, 2 on the second one and so on.

CodePudding user response:

Similar question

With succ/2:

nat(N) :-
    nat(0, N).

nat(N, N).
nat(N0, N) :-
    succ(N0, N1),
    nat(N1, N).

Or with call_nth/2:

nat(0).
nat(N) :-
    call_nth(repeat, N).

Now, all natural numbers:

?- nat(N).

CodePudding user response:

incrementing(Lower, Increment, N) :-
    integer(Lower),
    integer(Increment),
    Increment @>= 1,
    (   nonvar(N) ->
        integer(N),
        % Fast integer comparison
        N @>= Lower,
        % No more than 1 possible answer
        incrementing_nonvar_(Lower, Increment, N)
    ;   incrementing_var_(Lower, Increment, N)
    ).

incrementing_nonvar_(Lower, Increment, N) :-
    % Can calculate, faster than iterating
    Diff is N - Lower,
    divmod(Diff, Increment, _, 0).

incrementing_var_(Lower, _Increment, Lower).
incrementing_var_(Lower, Increment, N) :-
    Lower1 is Lower   Increment,
    incrementing_var_(Lower1, Increment, N).

Results in swi-prolog:

?- incrementing(5, 3, N).
N = 5 ;
N = 8 ;
N = 11 ;
N = 14 ...

?- incrementing(5, 3, 11).
true.

?- incrementing(5, 3, 12).
false.

Could wrap this, for convenience, e.g.:

iterate(N) :-
    incrementing(0, 1, N).

Results:

?- iterate(-1).
false.

?- iterate(2).
true.

?- iterate(N).
N = 0 ;
N = 1 ;
N = 2 ;
N = 3 ...
  • Related