# The First Class Function

> Functions travel as values - prove you can pass one around.

Canonical URL: <https://datadriven.io/problems/the_first_class_function>

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Implement two functions: apply_twice(f, x) returns f(f(x)); compose(f, g) returns lambda x: f(g(x)). The test harness calls test cases with 'f', 'g', 'x', 'op' and a registry of named functions ('double' = x*2, 'inc' = x+1). Return the list of results.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests understanding of **first-class functions and function composition** in Python. It probes whether a candidate can pass functions as arguments, return functions from functions, and chain transformations.

---

### Break down the requirements

#### Step 1: Implement apply_twice(f, x)

Call `f(x)` to get an intermediate result, then call `f` on that result and return it.

#### Step 2: Implement compose(f, g)

Return a new function that, when called with x, computes `f(g(x))`.

---

### The solution

**Higher-order function application and composition**

```python
def apply_twice(f, x):
    first = f(x)
    result = f(first)
    return result
def compose(f, g):
    def composed(x):
        inner = g(x)
        result = f(inner)
        return result
    return composed
```

> **Time and Space Complexity**
>
> **Time:** O(1) per call (excluding the cost of f and g themselves).
> 
> **Space:** O(1). The closure captures only the function references.

> **Interviewers Watch For**
>
> Whether you understand closures. The `composed` function captures `f` and `g` in its closure scope. This is a fundamental Python concept.

> **Common Pitfall**
>
> Getting the composition order wrong. `compose(f, g)` should apply `g` first, then `f`. Some candidates reverse this.

---

## Common follow-up questions

- How would you compose an arbitrary number of functions? _(Tests `functools.reduce` with a compose helper or a loop.)_
- What is the difference between a closure and a class with __call__? _(Tests understanding of two ways to create callable objects.)_
- How does this relate to decorators? _(Tests that decorators are syntactic sugar for function wrapping, which is a form of composition.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_first_class_function)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.