Skip to content

Update higher-order-functions.md #1351

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
Jul 8, 2019
Merged
Changes from all commits
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
6 changes: 5 additions & 1 deletion _tour/higher-order-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ The terminology can get a bit confusing at this point, and we use the phrase
"higher order function" for both methods and functions that take functions as parameters
or that return a function.

In a pure Object Oriented world a good practice is to avoid exposing methods parameterized with functions that might leak object's internal state. Leaking internal state might break the invariants of the object itself thus violating encapsulation.

One of the most common examples is the higher-order
function `map` which is available for collections in Scala.
```tut
Expand Down Expand Up @@ -58,7 +60,7 @@ case class WeeklyWeatherForecast(temperatures: Seq[Double]) {
def forecastInFahrenheit: Seq[Double] = temperatures.map(convertCtoF) // <-- passing the method convertCtoF
}
```
Here the method `convertCtoF` is passed to `forecastInFahrenheit`. This is possible because the compiler coerces `convertCtoF` to the function `x => convertCtoF(x)` (note: `x` will
Here the method `convertCtoF` is passed to the higher order function `map`. This is possible because the compiler coerces `convertCtoF` to the function `x => convertCtoF(x)` (note: `x` will
be a generated name which is guaranteed to be unique within its scope).

## Functions that accept functions
Expand Down Expand Up @@ -102,6 +104,8 @@ object SalaryRaiser {
The new method, `promotion`, takes the salaries plus a function of type `Double => Double`
(i.e. a function that takes a Double and returns a Double) and returns the product.

Methods and functions usually express behaviours or data transformations, therefore having functions that compose based on other functions can help building generic mechanisms. Those generic operations defer to lock down the entire operation behaviour giving clients a way to control or further customize parts of the operation itself.

## Functions that return functions

There are certain cases where you want to generate a function. Here's an example
Expand Down