# Higher-Order Functions

This chapter is from the book

## 9.7 Closures

Recall our first implementation of function greaterThan, in Listing 9.3:

Scala

```def greaterThan(bound: Int): Int => Boolean =
def greaterThanBound(x: Int): Boolean = x > bound
greaterThanBound```

You can apply greaterThan to different values to produce different functions. For example, greaterThan(5) is a function that tests if a number is greater than 5, while greaterThan(100) is a function that tests if a number is greater than 100:

Scala

```val gt5   = greaterThan(5)
val gt100 = greaterThan(100)

gt5(90)   // true
gt100(90) // false```

The question to ponder is this: In the gt5(90) computation, which compares 90 to 5, where does the value 5 come from? A 5 was pushed on the execution stack as local variable bound for the call greaterThan(5), but this call has been completed, and the value removed from the stack. In fact, another call has already taken place with local variable bound equal to 100. Still, gt5(90) compares to 5, not to 100. Somehow, the value 5 of variable bound was captured during the call greaterThan(5), and is now stored as part of function gt5.

The terminology surrounding this phenomenon is somewhat ambiguous, but most sources define closures to be functions associated with captured data.6 When a function, like greaterThanBound, uses variables in its body other than its arguments—here, bound—these variables must be captured to create a function value.

Closures are sometimes used in functional programming languages as a way to add state to a function. For instance, a function can be “memoized” (a form of caching) by storing the inputs and outputs of previous computations:

Scala

```def memo[A, B](f: A => B): A => B =
val store = mutable.Map.empty[A, B]

def g(x: A): B =
store.get(x) match
case Some(y) => y
case None =>
val y = f(x)
store(x) = y
y
g```

Function memo is a higher-order function. Its argument f is a function of type A => B. Its output is another function, g, of the same type. Function g is functionally equivalent to f—it computes the same thing—but stores every computed value into a map. When called on some input x, function g first looks up the map to see if value f(x) has already been calculated and if so, returns it. Otherwise, f(x) is computed, using function f, and stored in the map before being returned. You apply memo to a function to produce a memoized version of that function:

Scala

```val memoLength: String => Int = memo(str => str.length)

memoLength("foo") // invokes "foo".length and returns 3
memoLength("foo") // returns 3, without invoking method length```

Function memoLength is a function from strings to integers, like str => str.length. It calculates the length of a string and stores it. The first time you call memoLength("foo"), the function invokes method length on string "foo", stores 3, and returns 3. If you call memoLength("foo") again, value 3 is returned directly, without invoking method length of strings. Another invocation memo(str => str.length) would create a new closure with its own store map.

What is captured by a closure is a lexical environment. This environment contains function arguments, local variables, and fields of an enclosing class, if any:

Scala

##### Listing 9.7: Example of a function writing in its closure.
```def logging[A, B](name: String)(f: A => B): A => B =
var count = 0
val logger = Logger.getLogger("my.package")

def g(x: A): B =
count += 1
logger.info(s"calling \$name (\$count) with \$x")
val y = f(x)
logger.info(s"\$name(\$x)=\$y")
y

g```

Like memo, function logging takes a function of type A => B as its argument and produces another function of the same type. The returned function is functionally equivalent to the input function, but it adds logging information, including the input and output of each call and the number of invocations:

Scala

```val lenLog: String => Int = logging("length")(str => str.length)

lenLog("foo")
// INFO: calling length (1) with foo
// INFO: length(foo)=3

lenLog("bar")
// INFO: calling length (2) with bar
// INFO: length(bar)=3```

For this to work, the returned closure g needs to maintain references to arguments name and f, as well as to local variables count and logger.

Note that variable count is modified when the closure is called. Writing into closures can be a powerful mechanism, but it is also fraught with risks:

Scala

```// DON'T DO THIS!
val multipliers = Array.ofDim[Int => Int](10)

var n = 0
while n < 10 do
multipliers(n) = x => x * n
n += 1```

This code attempts to create an array of multiplying functions: It fills the array with functions of type Int => Int defined as x => x * n. The idea is that multipliers(i) should then be x => x * i, a function that multiplies its argument by i. However, as written, the implementation does not work:

Scala

```val m3 = multipliers(3)
m3(100) // 1000, not 300```

All the functions stored in the array close over variable n and share it. Since n is equal to 10 at the end of the loop, all the functions in the array multiply their argument by 10 (at least, until n is modified). Some languages, including Java, emphasize safety over flexibility and do not allow local variables captured in closures to be written.

As with other forms of implicit references (e.g., inner classes), you need to be aware of closures to avoid tricky bugs caused by unintended sharing. This is especially true when closing over mutable data. As always, emphasizing immutability tends to result in safer code.

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.