easy +10 pts

Bind First Argument

Create a decorator that fixes the first positional argument of a function.

Write a decorator `bind_first_arg` that takes a value `x` and returns a decorator. When applied to a function `f`, the decorated function should call `f` with `x` as the first positional argument, followed by any positional and keyword arguments passed to the decorated call. The function is defined as follows: ```python def bind_first_arg(x): ... ``` The decorator should return a new function that, when called with `*args, **kwargs`, returns the result of `f(x, *args, **kwargs)`. The original function's behavior (including return value) should be preserved. You may assume `x` is given at decoration time and does not change. For example, the following code should work: ```python @bind_first_arg(1) def add(a, b): return a + b ``` Then `add(2)` returns `3`. Similarly, after: ```python @bind_first_arg(10) def multiply(a, b, c): return a * b * c ``` `multiply(2, 3)` returns `60`. Also, you can bind built-in functions like `pow`: after `power = bind_first_arg(2)(pow)`, `power(3)` returns `8`.

Constraints

The decorated function can be called with any number of positional and keyword arguments. The function `f` can be any callable, including built-ins, lambdas, or user-defined functions. The implementation should not modify the original function or use global state. The solution must be correct for any number of arguments.

Example

>>> @bind_first_arg(1)
... def add(a, b):
...     return a + b
>>> add(2)
3
>>> @bind_first_arg(10)
... def multiply(a, b, c):
...     return a * b * c
>>> multiply(2, 3)
60
>>> power = bind_first_arg(2)(pow)
>>> power(3)
8
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

The outer function should return a decorator function.
The decorator should return a wrapper function that accepts *args and **kwargs.
Use a closure to capture x.
Call the original function with x passed first.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.