To begin, we can finish our implementation of the Mortgage sub-module with a real implementation of the payment function.
Let's see how this works:
- The payment function takes a loan amount, an annual interest rate, the number of years for the loan, and calculates the monthly payment of the loan, as shown in the following code:
# Mortgage.jl
module Mortgage
function payment(amount, rate, years)
monthly_rate = rate / 12.0
factor = (1 + monthly_rate) ^ (years * 12.0)
return amount * (monthly_rate * factor / (factor - 1))
end
end # module
- At this point, the Calculator module should be able to use the Mortgage sub-module as if it's yet another module, except that the notation to get access to the sub-module requires a relative path that is prefixed with a dot notation:
# Calculator.jl
module Calculator
# include sub-modules
include("Mortgage.jl")
using .Mortgage: payment
# functions for the main module
include("funcs.jl")
end # module
Here, we have brought the payment function into the current scope of the sub-module via using .Mortgage: payment.
- In order to organize our code better, we have also moved the functions into a separate file called funcs.jl. The code is shown as follows:
# funcs.jl - common calculation functions
export interest, rate, mortgage
function interest(amount, rate)
return amount * (1 + rate)
end
function rate(amount, interest)
return interest / amount
end
# uses payment function from Mortgage.jl
function mortgage(home_price, down_payment, rate, years)
return payment(home_price - down_payment, rate, years)
end
As we can see, the new mortgage function can use the payment function from the Mortgage sub-module now.