【发布时间】:2013-12-23 04:24:45
【问题描述】:
我需要 Prolog 中的谓词,它会产生如下进展:
[0, 0.1, 0.2, 0.3, ..., 定义结束]。
我只知道内置的 between/3,但它只产生像 0,1,2,3 这样的整数...
感谢您的帮助!!
【问题讨论】:
标签: prolog
我需要 Prolog 中的谓词,它会产生如下进展:
[0, 0.1, 0.2, 0.3, ..., 定义结束]。
我只知道内置的 between/3,但它只产生像 0,1,2,3 这样的整数...
感谢您的帮助!!
【问题讨论】:
标签: prolog
这里是之间的减少(没有错误检查,它可能对某些浮点数有一些精度错误):
between_step(First, Last, Step, Var) :-
NrSteps is integer((Last - First) / Step),
between(0, NrSteps, TempVar),
Var is First + Step * TempVar.
一些使用示例:
?- between_step(2.5, 3, 0.1, X).
X = 2.5 ?;
X = 2.6 ?;
X = 2.7 ?;
X = 2.8 ?;
X = 2.9 ?;
X = 3.0
?- findall(X, between_step(0, 1, 0.1, X), Xs).
Xs = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
yes
【讨论】:
您可以尝试以下类似的方法,但如果您问我,通过回溯模拟程序循环的构造类似于 Prolog code smell,表明您的设计与 Prolog 的工作方式存在阻抗不匹配。
for(From,To,Step,From) :- % Unify the incremental value with the current 'From'
Step > 0 , % - when the 'Step' is positive, and
From =< To . % - the 'To' limit has not been exceeded.
for(From,To,Step,Inc) :- % On backtracking...
Step > 0 , % - when the 'Step' is positive,
From < To , % - and the 'To' limit has not yet been reached
Next is From+Step , % - increment 'From'
for(Next,To,Step,Inc) . % - and recurse down.
for(From,To,Step,From) :- % Unify the incremental value with the current 'From'
Step < 0 , % - when the 'Step' is negative, and
From >= To . % - the 'To' limit has not been exceeded
for(From,To,Step,Inc) :- % On backtracking...
Step < 0 , % - when the 'Step' is negative, and
From > To , % - the 'To' limit has not yet been reached
Next is From+Step , % - decrement 'From'
for(Next,To,Step,Inc) . % - and recurse down
【讨论】: