- Scala Programming Projects
- Mikael Valot Nicolas Jorand
- 200字
- 2021-07-23 16:25:21
Ensuring termination
We are not quite done yet because our function might loop indefinitely. Imagine that you always spend more than what you earn. You will never be able to save enough to retire, even if you live a million years! Here is a unit test highlighting this:
"RetCalc.nbOfMonthsSaving" should {
"calculate how long I need to save before I can retire" in {...}
"not crash if the resulting nbOfMonths is very high" in {...}
"not loop forever if I enter bad parameters" in {
val actual = RetCalc.nbOfMonthsSavingV2(
interestRate = 0.04 / 12, nbOfMonthsInRetirement = 40 * 12,
netIncome = 1000, currentExpenses = 2000, initialCapital = 10000)
actual should === (Int.MaxValue)
}
}
We decided to use a special value Int.MaxValue to indicate that nbOfMonths is infinite. This is not very pretty, but we will see in the next chapter how we can model this better with Option or Either. This is good enough for now.
To make the test pass, we just need to add an if statement:
def nbOfMonthsSaving(interestRate: Double, nbOfMonthsInRetirement: Int,
netIncome: Int, currentExpenses: Int, initialCapital: Double): Int = {
@tailrec
def loop(nbOfMonthsSaving: Int): Int = {...}
if (netIncome > currentExpenses)
loop(0)
else
Int.MaxValue
}
推薦閱讀
- 計算機網(wǎng)絡(luò)與通信(第2版)
- Building Django 2.0 Web Applications
- Spring Boot 2.0 Projects
- 重新定義Spring Cloud實戰(zhàn)
- 物聯(lián)網(wǎng)時代
- 網(wǎng)絡(luò)安全技術(shù)與解決方案(修訂版)
- 物聯(lián)網(wǎng)技術(shù)與應(yīng)用
- Getting Started with Grunt:The JavaScript Task Runner
- Spring 5.0 Projects
- TD-LTE無線網(wǎng)絡(luò)規(guī)劃與設(shè)計
- 中國互聯(lián)網(wǎng)發(fā)展報告2021
- 深入理解計算機網(wǎng)絡(luò)
- 移動互聯(lián)網(wǎng)環(huán)境下的核心網(wǎng)剖析及演進(jìn)
- Corona SDK Application Design
- 智能物聯(lián)安防視頻技術(shù)基礎(chǔ)與應(yīng)用