要模拟这样的简单循环:
start = something;
incr = something_else;
end = yet_something_else; /* all three are numerical values, int or float */
while (start <= end) {
/* do something for its side effect, for example: */
printf("%d %d\n", start, start*start);
start += incr;
}
我可以写:
loop1(Start, End, _Incr) :-
Start > End, !. % yes, the cut is necessary!
loop1(Start, End, Incr) :-
Start =< End,
/* do something for its side effect, for example */
format('~d ~d~n', [Start, Start*Start]),
Next is Start + Incr,
loop1(Next, End, Incr).
或者:
loop2(Start, End, Incr) :-
( Start =< End
-> format('~d ~d~n, [Start, Start*Start]),
Next is Start + Incr,
loop2(Next, End, Incr)
; true
).
loop/3
必须(并且总是会)调用实例化为数字的所有参数。
我应该使用第二个版本,对吧?存在疑问的唯一原因是 if-then-else 结构在 Prolog 介绍材料中几乎没有,我不知道为什么(例如,立即学习 Prolog!,否则一个很好的介绍材料,不甚至不提!)。与此同时,每一个方向都有随意飞舞的切口。
谢谢您的帮助!