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).
usage:
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.
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' )).
yields
?- icecream(4).
()
(())
(( ))
(( ))
/////
/
/
/
/
/
true.
note: loop in the second snippet is unrelated to first...