Scala 函数式编程入门:从基础到多态
1. 高阶函数初体验
在 Scala 中,我们可以定义一些简单的函数,例如计算绝对值和阶乘的函数。下面是一个包含阶乘函数的简单程序示例:
object MyProgram:
private def formatAbs(x: Int) =
val msg = "The absolute value of %d is %d."
msg.format(x, abs(x))
private def formatFactorial(n: Int) =
val msg = "The factorial of %d is %d."
msg.format(n, factorial(n))
@main def printAbsAndFactorial: Unit =
println(formatAbs(-42))
println(formatFactorial(7))
这里的 formatAbs 和 formatFactorial 函数非常相似,我们可以将它们泛化为一个高阶函数 formatResult :
def formatResult(name: String, n: Int, f: Int => Int) =
val msg = "The %s of %d is %d."
msg.format(name, n, f(n))
超级会员免费看
订阅专栏 解锁全文
60

被折叠的 条评论
为什么被折叠?



