Search code examples
prolog

Improving Prolog Program with Red Cuts


I wrote a Prolog program that calculates the price of a hotel room based on season and type of room. Can this program be improved by using red cuts?

season(Month, Season) :- member(Month, [may,sep]), Season = low.
season(Month, Season) :- member(Month, [jul,aug]), Season = high.
season(Month, Season) :- Month = jun, Season = mid.

room_price(basic, 80).
room_price(deluxe, 100).
room_price(superior, 120).

room_price(Type, Month, Price) :-
    season(Month, low),
    room_price(Type, BasicPrice),
    Price is BasicPrice * 0.8, !.

room_price(Type, Month, Price) :-
    season(Month, high),
    room_price(Type, BasicPrice),
    Price is BasicPrice * 1.2, !.

room_price(Type, Month, Price) :-
    season(Month, mid),
    room_price(Type, Price).

Solution

  • Use an auxiliary predicate with the season as the first argument, taking advantage of Prolog first-argument indexing:

    room_price(Type, Month, Price) :-
        season(Month, Season),
        room_price(Season, Type, Month, Price).
    
    room_price(low, Type, Month, Price) :-
        room_price(Type, BasicPrice),
        Price is BasicPrice * 0.8.
    
    room_price(high, Type, Month, Price) :-
        room_price(Type, BasicPrice),
        Price is BasicPrice * 1.2.
    
    room_price(mid, Type, Month, Price) :-
        room_price(Type, Price).