英文:
How to increment using 'functional programming' in golang
问题
我从exercism得到了一个代码挑战,题目是“利息很有趣”。我尽量使用函数式编程的方法来解决问题,但是我发现我的最后一个函数使用了两个可变变量。
package interest
import "math"
// InterestRate返回提供的余额的利率。
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计算提供的余额的利息。
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计算年度余额更新,考虑到利率。
func AnnualBalanceUpdate(balance float64) float64 {
return balance + Interest(balance)
}
// YearsBeforeDesiredBalance计算达到目标余额所需的最少年数:
func YearsBeforeDesiredBalance(balance, targetBalance float64) int {
year := 0
for balance < targetBalance {
balance = AnnualBalanceUpdate(balance)
year++
}
return year
}
我的代码还有更多的函数式编程方法吗?
英文:
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?
答案1
得分: 2
递归通常用于这个目的:
func YearsBeforeDesiredBalance(balance, targetBalance float64, year int) int {
if balance >= targetBalance {
return year
}
return YearsBeforeDesiredBalance(AnnualBalanceUpdate(balance), targetBalance, year + 1)
}
请注意,Go语言不是一种函数式编程语言,可能不会对这种递归进行优化。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论