Skip to content

Rewrote nested functions tour #735

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 29, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions tutorials/tour/_posts/2017-02-13-nested-functions.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
layout: tutorial
title: Nested Functions
title: Nested Methods

disqus: true

Expand All @@ -11,25 +11,27 @@ next-page: currying
previous-page: higher-order-functions
---

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:
In Scala it is possible to nest function definitions. The following object provides a `factorial` function for computing the factorial of a given number:

```tut
object FilterTest extends App {
def filter(xs: List[Int], threshold: Int) = {
def process(ys: List[Int]): List[Int] =
if (ys.isEmpty) ys
else if (ys.head < threshold) ys.head :: process(ys.tail)
else process(ys.tail)
process(xs)
object FactorialTest extends App {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would use def main here

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's clearer if all of the examples are in worksheet mode and not inside classes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@travis032654 I have rewritten the example in worksheet mode

def factorial(x: Int): Int = {
def fact(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else fact(x - 1, x * accumulator)
}
fact(x, 1)
}
println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))
println("Factorial of 2: " + factorial(2))
println("Factorial of 3: " + factorial(3))
}
```

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

The output of this program is:

```
List(1,2,3,4)
Factorial of 2: 2
Factorial of 3: 6
```