序言:添加列表

时间:2019-07-06 17:52:24

标签: prolog

我不知道我是否要解释它是可以理解的,但是基本上,我在这一点上有一个问题:“如果距离小于190,则佣金为10%,如果距离大于190佣金为15%。”。我要怎么做才能包括距离之和?

conexion(a, b, 100).
conexion(a, c, 250).
conexion(b, c, 10).
conexion(b, d, 100).
conexion(c, d, 50).

route(A, B, Route):- conexion(A, B, C), Route = [[A, B]].
route(A, B, Route):- conexion(A, X, C), route = (X, B, Route1), Route = [[A, X] | Route1].

route2(A, B, Route, Dist):- conexion(A, B, C), Route = [[A, B]], Dist = [C].
route2(A, B, Route, Dist):- conexion(A, X, C), route2 = (X, B, Route1, Dist1), Route = [[A, X] | Route1], Dist = [C | Dist1].

sum(List, Cnt):- List = [], Cnt = 0.
sum(List, Cnt):- List = [X | R], sum(R, Cnt1), Cnt is Cnt1 + X.

distance(X, Y, Total):- route2(X, Y, route, Dist), sum(Dist, Total).

查询时:

route2(a, b, R, D), sum(D, S).

输出:

R = [[a, b]],
D = [100],
S = 100 ;
false.

1 个答案:

答案 0 :(得分:1)

我认为您在这里做了太多列表处理。我们可以在此处定义一个简单的route/4谓词,该谓词可以计算出距离和距离,如:

route(A, A, [A], 0).
route(A, C, [A|R], Dist) :-
    conexion(A, B, D0),
    route(B, C, R, D1),
    Dist is D0 + D1.

或者我们可以通过以下方式使用尾部呼叫优化:

route(A, C, R, D) :-
    route(A, C, R, 0, D).

route(A, A, [A], D, D).
route(A, C, [A|R], D0, D) :-
    conexion(A, B, D1),
    D2 is D0 + D1,
    route(B, C, R, D2, D).

然后我们可以添加一个谓词route_with_commission,该谓词可以简单地计算佣金。我们可以首先引入一个帮助谓词来计算佣金:

commission(D, C) :-
    D < 190,
    !,
    C is 0.1 * D.
commission(D, C) :-
    D >= 190,
    C is 0.15 * D.

,然后将两者结合:

route_with_commission(A, C, R, D, Commission) :-
    route(A, C, R, D),
    commission(D, Commission).