Advanced FP Patterns — Series 2

Preview — 3 of 10 questions

What is the output of the following code?

javascript
from functools import partial
import inspect

def curry(func):
    sig = inspect.signature(func)
    n_params = len(sig.parameters)

    def curried(*args):
        if len(args) >= n_params:
            return func(*args)
        return curry(partial(func, *args))
    return curried

@curry
def add3(a, b, c):
    return a + b + c

print(add3(1)(2)(3))
print(add3(1, 2)(3))
print(add3(1, 2, 3))
A6, 6, 6
B6, TypeError: curried() takes from 0 to 1 positional arguments, 6 — calling with two arguments at once isn't supported by this curry implementation.
C<function curried at 0x...>, <function curried at 0x...>, 6 — the first two calls just return partially-applied functions, not print-friendly.
D1, 3, 6 — each call to curried returns only the newly supplied arguments, not the accumulated result.

What is the output of the following code?

javascript
from itertools import islice

nums = range(20)
result = list(islice(nums, 2, 15, 3))
print(result)
A[2, 3, 4, 5, ..., 14] (every value from 2 to 14) — the third argument is ignored.
B[2, 5, 8, 11, 14]
C[2, 15, 3] — islice's three arguments are treated as individual values to select, not as start/stop/step.
D[0, 3, 6, 9, 12] — islice ignores the given start/stop and just steps from the beginning.

What is the output of the following code?

javascript
class Maybe:
    def __init__(self, value):
        self.value = value

    def map(self, func):
        if self.value is None:
            return self
        return Maybe(func(self.value))

    def __repr__(self):
        return f"Maybe({self.value})"

print(Maybe(5).map(lambda x: x * 2).map(lambda x: x + 1))
print(Maybe(None).map(lambda x: x * 2).map(lambda x: x + 1))
AMaybe(11), then TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
BMaybe(11), then Maybe(0) — a None value defaults to 0 before further mapping.
CMaybe(11), Maybe(None)
D11, None — Maybe doesn't actually wrap its result in another Maybe instance.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.