简体   繁体   English

如何迭代 prolog 中的空输入?

[英]how iterate on an empty input in prolog?

i want to know if there are any methods to achieve an iteration in Prolog passing an empty input.我想知道是否有任何方法可以在 Prolog 中通过空输入实现迭代。 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.例如,我希望第一次迭代为 0,下一次迭代为 1,第二次迭代为 2,依此类推。

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:结果 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, eg:为了方便起见,可以包装一下,例如:

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

Results:结果:

?- iterate(-1).
false.

?- iterate(2).
true.

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

Similar question 类似的问题

With succ/2 :使用succ/2

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

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

Or with call_nth/2 :或使用call_nth/2

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

Now, all natural numbers:现在,所有自然数:

?- nat(N).

Example: iterate() is my query and every time i call it i want that the output is 0 first time 1 second time and so on.示例: iterate() 是我的查询,每次我调用它时,我希望 output 第一次为 0,第二次为 0,依此类推。

If you store the state in the Prolog database and don't mind the output being by side effect and can deal with not using () when calling it, then:如果您将 state 存储在 Prolog 数据库中,并且不介意 output 有副作用并且可以在调用时处理不使用 () 的情况,则:

:- dynamic(iterate_counter/1).

iterate_counter(0).


iterate() :-
    iterate_counter(X),
    writeln(X),
    succ(X, Y),
    retract(iterate_counter(X)),
    assert(iterate_counter(Y)).
?- iterate, iterate, iterate.
0
1
2

From your comment:从您的评论中:

Example: iterate() is my query and every time i call it i want that the output is 0 first time 1 second time and so on.示例: iterate()是我的查询,每次我调用它时,我希望 output 第一次为 0,第二次为 0,依此类推。

Shouldn't be any more difficult than this:应该不会比这更困难:

increment(N) :- inc(0,1,N).

inc(C , _ , C ) .
inc(C , S , N ) :- C1 is C+S, inc(C1,S,N).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM