搜索Prolog谓词

时间:2013-12-18 21:27:45

标签: prolog

我需要Prolog中的谓词,它会产生如下的进展:

[0,0.1,0.2,0.3,...,定义结束]。

我只知道/ 3之间的内置,但只产生0,1,2,3之类的整数......

感谢您的帮助!!

2 个答案:

答案 0 :(得分:4)

这是一个减少到之间(没有错误检查,它可能有一些浮点数的精度错误):

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

答案 1 :(得分:0)

你可以尝试类似下面这样的东西,但是如果你问我,通过回溯来模仿程序循环的构造是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