【问题标题】:Prolog sum distance between list of nodes ids节点ID列表之间的Prolog总和距离
【发布时间】:2020-09-14 10:23:38
【问题描述】:
node(1,22,44).
node(2,43,53).
node(3,23,12).

distance(Id1,Id2,D) :-
    node(Id1,X1,Y1),
    node(Id2,X2,Y2),
    D is sqrt((X2-X1)^2 + (Y2-Y1)^2).

distancePath([X,Y],D) :-
    distance(X,Y,D).
distancePath([H,X|T],Distance) :-
    distancePath([X|T],Rest),
    distance(H,X,D),
    Aux is Rest + D,
    Distance is Distance + Aux.

我在 distancePath 上遇到了一些问题,因为当我运行 distancePath([1,2,3],Distance). 时,它给了我“(is)/2 的参数 2 中的实例化错误”有人可以帮助我吗?

【问题讨论】:

    标签: prolog instantiation-error


    【解决方案1】:

    Distance is Distance + Aux. 没有多大意义。变量是不可变的,这意味着一旦设置变量将在 Prolog 评估的该分支中保持相同的值。此外,Distance 是无限的,因此会出现错误。

    您实际上已经有了Distance 的值:它是Aux,因为它是列表中Rest 的距离加上D 的距离:

    distancePath([X,Y], D) :-
        distance(X,Y,D).
    
    distancePath([H,X|T], Aug) :-
        distancePath([X|T],Rest),
        distance(H,X,D),
        Aux is Rest + D.

    这给了我们:

    ?- distancePath([1,2,3], D).
    D = 68.4652982294199 ;
    false.
    

    然而,上面的方法不是很有效:它没有使用尾递归,而且你多次执行 cons 构造函数的解包。您可以使用辅助谓词来提高效率:

    distancePath([X|T], Result) :-
        distancePath(T, X, 0, Result).
    
    distancePath([], _, D, D).
    distancePath([J|T], I, Di, Do) :-
        distance(I, J, Dd),
        D2 is Di + Dd,
        distancePath(T, J, D2, Do).

    【讨论】:

      猜你喜欢
      • 2011-10-12
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多