“Nested functions”的版本间差异
本页内容
(创建页面,内容为“{{DISPLAYTITLE:内嵌函数}}7 = Scala 函数嵌套 = Scala 函数 我们可以在 Scala 函数内定义函数,定义在函数内的函数称之为局部函数。 以下实例我们实现阶乘运算,并使用内嵌函数: <sample title="" desc="" lang="scala" hererun="1"> object Test { def main(args: Array[String]) { println( factorial(0) ) println( factorial(1) ) println( factoria…”) |
无编辑摘要 |
||
第8行: | 第8行: | ||
以下实例我们实现阶乘运算,并使用内嵌函数: | 以下实例我们实现阶乘运算,并使用内嵌函数: | ||
< | <pre> | ||
object Test { | object Test { | ||
def main(args: Array[String]) { | def main(args: Array[String]) { | ||
第19行: | 第19行: | ||
def factorial(i: Int): Int = { | def factorial(i: Int): Int = { | ||
def fact(i: Int, accumulator: Int): Int = { | def fact(i: Int, accumulator: Int): Int = { | ||
if (i | if (i <= 1) | ||
accumulator | accumulator | ||
else | else | ||
第27行: | 第27行: | ||
} | } | ||
} | } | ||
</pre> | |||
执行以上代码,输出结果为: | 执行以上代码,输出结果为: | ||
< | <pre> | ||
$ scalac Test.scala | $ scalac Test.scala | ||
$ scala Test | $ scala Test | ||
第37行: | 第37行: | ||
2 | 2 | ||
6 | 6 | ||
</pre> | |||
[[scala functions|Scala 函数]] | [[scala functions|Scala 函数]] |
2022年10月14日 (五) 16:51的最新版本
Scala 函数嵌套
我们可以在 Scala 函数内定义函数,定义在函数内的函数称之为局部函数。
以下实例我们实现阶乘运算,并使用内嵌函数:
object Test { def main(args: Array[String]) { println( factorial(0) ) println( factorial(1) ) println( factorial(2) ) println( factorial(3) ) } def factorial(i: Int): Int = { def fact(i: Int, accumulator: Int): Int = { if (i <= 1) accumulator else fact(i - 1, i * accumulator) } fact(i, 1) } }
执行以上代码,输出结果为:
$ scalac Test.scala $ scala Test 1 1 2 6