'How to increment using 'functional programming' in golang

I got a code challenge from exercism title: Interest is interesting. I solved the questions with extra challenge from myself: use functional approach as much as possible. However, I found my last function use two mutable variables.

package interest

import "math"

// InterestRate returns the interest rate for the provided balance.
func InterestRate(balance float64) float32 {
    switch {
    case balance < 0:
        return 3.213
    case balance < 1000:
        return 0.5
    case balance < 5000:
        return 1.621
    default:
        return 2.475
    }
}

// Interest calculates the interest for the provided balance.
func Interest(balance float64) float64 {
    if balance < 0 {
        return -math.Abs(balance) * float64(InterestRate(balance)) / 100.0
    }
    return math.Abs(balance) * float64(InterestRate(balance)) / 100.0
}

// AnnualBalanceUpdate calculates the annual balance update, taking into account the interest rate.
func AnnualBalanceUpdate(balance float64) float64 {
    return balance + Interest(balance)
}

// YearsBeforeDesiredBalance calculates the minimum number of years required to reach the desired balance:
func YearsBeforeDesiredBalance(balance, targetBalance float64) int {
    year := 0
    for balance < targetBalance {
        balance = AnnualBalanceUpdate(balance)
        year++
    }
    return year
}

Is there any more 'functional programming' approach for my codes?



Solution 1:[1]

Recursion is usually used for this:

func YearsBeforeDesiredBalance(balance, targetBalance float64, year int) int {
    if balance >= targetBalance {
        return year
    }

    return YearsBeforeDesiredBalance(AnnualBalanceUpdate(balance), targetedBalance, year + 1)
}

Mind that Go is not a functional programming language and probably does not optimize this kind of recursion.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakub Dóka