% - The classic CLP(R) mortgage calculation example

% P: Principal, i.e., the balance at the beginning
% T: Term, i.e., the number of interest periods (e.g., years)
% I: Interest rate, where, e.g., 0.1 means 10% by interest period
% B: Balance at the end of the period
% MP: Monthly Payment amount for each interest period

:- module(_,_).
:- use_package(clpr).
% Or, we can use clpq for exact calculations
% :- use_package(clpq).

mg(P, T, I, B, MP):-
    T .=. 1,
    B + MP .=. P * (1 + I).
mg(P, T, I, B, MP):-
    T .>. 1,
    P1 .=. P * (1 + I) - MP,
    T1 .=. T - 1,
    mg(P1, T1, I, B, MP).

% A simple query to calculate what the payments will be
% for a $1000 loan, 30 periods, at 3%, with balance 0 at the 
% end: 
% ?- mg(1000, 30, 0.03, 0, MP).

% What loan amount can we afford if we can pay $20 per period? 
% ?- mg(P, 30, 0.03, 0, 20).

% If we see it instead as an investment, calculate the balance 
% gained at the end for a given interest rate:
% ?- mg(1000, 30, 0.03, B, 0).
 
% Same, but making payments of $50 per period: 
% ?- mg(1000, 30, 0.03, B, -50).
