csanchez
csanchez

Reputation: 91

Prolog: add a list

I don't know if I'm going to explain it understandable, but basically, I have a problem doing this point: "If the distance is less than 190, the commission is 10%, if the distance is greater than 190 the commission is 15%.". What can I do to include a commision from the sum of the distance?

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).

When I do the query:

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

the output:

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

Upvotes: 1

Views: 81

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

I think you do too much list processing here. We can define a simple route/4 predicate here that calculates the rout together with the distance like:

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

or we can make use of tail-call-optimization with:

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).

We can then add a predicate route_with_commission, that simply calculates the commission. We can first introduce a helper predicate to calculate the commission:

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

and then combine the two:

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

Upvotes: 1

Related Questions