且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现“For循环"在序言上

更新时间:2022-12-07 08:06:55

我的幼稚实现,被视为/3之间的扩展

my naive implementation, to be seen as an extendend between/3

:- module(loop, [upto/4, downto/4]).

upto(Low,High,_Step,Low) :- Low =< High.
upto(Low,High,Step,Var) :-
    Inc is Low+Step,
    Inc =< High,
    upto(Inc, High, Step, Var).

downto(Low,High,_Step,High) :- Low =< High.
downto(Low,High,Step,Var) :-
    Dec is High-Step,
    Dec >= Low,
    downto(Low, Dec, Step, Var).

用法:

8 ?- forall(upto(0,6,3,V),writeln(V)).
0
3
6
true.

9 ?- forall(downto(0,6,3,V),writeln(V)).
6
3
0
true.

另一个例子,@今年提出的最简单的问题 Prolog编程大赛:

another example, the easiest question posed @ this year Prolog programming contest:

icecream(N) :-
    loop(N, top(N)),
    left, loop(N+1, center), nl,
    loop(N+1, bottom(N)).

:- meta_predicate loop(+, 1).

loop(XH, PR) :-
    H is XH,
    forall(between(1, H, I), call(PR, I)).

top(N, I) :-
    left, spc(N-I+1), pop,
    (   I > 1
    ->  pop,
        spc(2*(I-2)),
        pcl
    ;   true
    ),
    pcl, nl.

bottom(N, I) :-
    left, spc(I-1), put(), spc(2*(N-I+1)), put(/), nl.

center(_) :- put(/), put().

left :- spc(4).
pop :- put(0'().
pcl :- put(0')).
spc(Ex) :- V is Ex, forall(between(1, V, _), put(0' )).

产量

?- icecream(4).
        ()
       (())
      ((  ))
     ((    ))
    /////
            /
           /
          /
         /
        /
true.

注意:第二个片段中的循环与第一个片段无关...

note: loop in the second snippet is unrelated to first...