# What are Higher-Order Functions Used For?

Yeah, alright, higher-order functions are cool and stuff. But what are they used for?

The higher-ordering of a function can be thought of as maintaining a layer of memory outside of a given function. Consider this example:&#x20;

```python
def f(x):
    def g(y):
        return x + y
    return g

func = f(3)
```

Now, `func` has some memory, some data it can use, beyond just the `y` that can be passed into it as an argument. It has a way of remembering the `x` that was passed in to create it. This is the power of higher-order functions.

Not only can be store these external to the function values, we can develop ways to update them too. For example, consider a function that takes in an argument `x`, which is the number of times the function is allowed to run, and returns a fucntion. Calls to this function print the value passed in. Any more calls than the number `x`, and the function should print the string "Nope!" instead. This function returns another function that does the same thing.

You might immediately pick up on the fact that this cannot be done through just one layer of function — there is some information that needs to be retained *across function calls*. Higher-order functions allow us to do this.

```python
def f(x):
    def g(y):
        if x <= 0:
            print("Nope!")
        else:
            print(y)
        ...
    return g
```

As you might be able to tell from the `...` in the code, this function is not yet complete. While `f` returns `g` properly, what we haven't figured out yet is a way to decrement `x` when a function call happens. We know that `g` is supposed to essentially return another `g`. However, adding the line `return g` does not fix the updating the value of `x` problem. Is there a way we can do both?

You bet there is.

```python
def f(x):
    def g(y):
        if x <= 0:
            print("Nope!")
        else:
            print(y)
        return f(x-1)
    return g
```

What we've uncovered here is the general structure of many higher-order functions: where **the inner function calls the outer one and the outer function returns the inner one.**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://calnotes.gitbook.io/cs61a-guidebook/building-blocks/higher-order-functions/what-are-higher-order-functions-used-for.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
