Skip to content

Commit 8a9be51

Browse files
committed
Rewrote nested functions tour
1 parent 919471a commit 8a9be51

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed
Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tutorial
3-
title: Nested Functions
3+
title: Nested Methods
44

55
disqus: true
66

@@ -11,25 +11,27 @@ next-page: currying
1111
previous-page: higher-order-functions
1212
---
1313

14-
In Scala it is possible to nest function definitions. The following object provides a `filter` function for extracting values from a list of integers that are below a threshold value:
14+
In Scala it is possible to nest function definitions. The following object provides a `factorial` function for computing the factorial of a given number:
1515

1616
```tut
17-
object FilterTest extends App {
18-
def filter(xs: List[Int], threshold: Int) = {
19-
def process(ys: List[Int]): List[Int] =
20-
if (ys.isEmpty) ys
21-
else if (ys.head < threshold) ys.head :: process(ys.tail)
22-
else process(ys.tail)
23-
process(xs)
17+
object FactorialTest extends App {
18+
def factorial(x: Int): Int = {
19+
def fact(x: Int, accumulator: Int): Int = {
20+
if (x <= 1) accumulator
21+
else fact(x - 1, x * accumulator)
22+
}
23+
fact(x, 1)
2424
}
25-
println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))
25+
println("Factorial of 2: " + factorial(2))
26+
println("Factorial of 3: " + factorial(3))
2627
}
2728
```
2829

29-
_Note: the nested function `process` refers to variable `threshold` defined in the outer scope as a parameter value of `filter`._
30+
_Note: the nested function `fact` refers to variable `x` defined in the outer scope as a parameter value of `factorial`._
3031

3132
The output of this program is:
3233

3334
```
34-
List(1,2,3,4)
35+
Factorial of 2: 2
36+
Factorial of 3: 6
3537
```

0 commit comments

Comments
 (0)