登录
首页 >  Golang >  Go问答

如何在 golang 中使用“函数式编程”进行增量

来源:stackoverflow

时间:2024-02-12 18:18:19 204浏览 收藏

哈喽!今天心血来潮给大家带来了《如何在 golang 中使用“函数式编程”进行增量》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我收到了来自练习题目的代码挑战:兴趣就是有趣。我通过自己的额外挑战解决了这些问题:尽可能使用函数式方法。但是,我发现我的最后一个函数使用了两个可变变量。

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
}

我的代码还有更多的“函数式编程”方法吗?


正确答案


递归通常用于此目的:

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

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

请注意,go 不是函数式编程语言,可能不会优化这种递归。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>