【问题标题】:Searching for a Prolog predicate搜索 Prolog 谓词
【发布时间】:2013-12-23 04:24:45
【问题描述】:

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

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

我只知道内置的 between/3,但它只产生像 0,1,2,3 这样的整数...

感谢您的帮助!!

【问题讨论】:

    标签: prolog


    【解决方案1】:

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

    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
    

    【讨论】:

    • Mh,如果我调用“findall(X, between_step(0, 10, 0.1, X), Xs)”,我得到了解决方案:Xs = [0.0, 0.1, 0.2, 0.30000000000000004, 0.4 , 0.5, 0.6000000000000001, 0.7000000000000001, 0.8|。有什么建议可以解决吗?!
    • 你说的是 0.30000000000000004 而不是 0.3?
    • 是的!对不起,我没有提到它。
    • 那是因为浮点数是不精确的。但是许多 Prolog 系统在显示结果时试图纠正这个问题。在 B-Prolog 和 SWI Prolog 中,您的查询得到“..., 0.3, 0.4, 0.5, 0.6, ...”。您使用的是什么 Prolog 系统和版本?
    • 嗯,我怎样才能得到我的 Prolog 的版本?有谓词吗?找不到类似的东西.. :/ 我正在为 Mac OS X 使用 SWI-Prolog。
    【解决方案2】:

    您可以尝试以下类似的方法,但如果您问我,通过回溯模拟程序循环的构造类似于 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多