Building Map and Filter from a Reduce Foundation
Data Structure DesignModel answerLast updated
Implement a reduce operation, then express map and filter purely in terms of that reducer without independent iteration.
You need to explain and implement a reduce operation, then show how map and filter can be built entirely on top of it—without their own separate loops or traversals.
Part 1: Specify and Implement Reduce
Define the behavior of a reduce function. Your explanation should cover:
- The signature: what arguments does
reduceaccept? - The reducer callback: what parameters does it receive and what does it return?
- The accumulator: where does the initial value come from?
- Iteration order: in what sequence are elements processed?
- Empty collections: what does
reducereturn when given an empty input? - Invariants: what guarantee holds after processing each element?
Provide a concrete implementation in a language of your choice.
Part 2: Derive Map and Filter
Using only your reduce implementation, build:
- map: transforms each input element via a function, producing a collection of the same length
- filter: keeps only elements satisfying a predicate, potentially shrinking the output
Your implementations must:
- Use
reduceinternally—no separate iteration - Preserve input order
- Handle empty inputs correctly
- Not mutate the original collection
Part 3: Composition Example
Demonstrate how these operations compose by showing a short example that chains map and filter to transform some structured data (you may invent a simple hypothetical dataset like a list of records).
Constraints
- Pick one language and state its relevant semantics (e.g., whether arrays are immutable, whether callbacks can throw)
- Your reduce must be eager (not lazy)
- Explain any performance considerations related to accumulator updates
Clarifying Questions to Consider
- Should the initial accumulator be required or optional?
- Can reducer callbacks mutate external state or raise exceptions?
- Must map and filter return new collections or may they modify in place?
Hints
Hint 1
The reducer callback typically receives (accumulator, current_element) and returns the next accumulator.
Hint 2
For map, the accumulator can be a growing collection; for filter, conditionally add elements based on the predicate.
Hint 3
Composition means passing the output of one operation as input to the next—no intermediate materialization tricks needed.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
A strong answer demonstrates understanding of higher-order functions, careful handling of accumulators, and clean composition.
Part 1: Reduce Specification and Implementation
Signature and Semantics
reduce(collection, reducer_fn, initial_accumulator) → final_accumulator
- reducer_fn:
(accumulator, element) → new_accumulator
Takes the current accumulated state and one element, returns the updated state. - initial_accumulator: The starting value before processing any elements.
- Iteration order: Left-to-right (though right-to-left variants exist, this baseline assumes left-fold).
- Empty input: Returns
initial_accumulatorunchanged. - Invariant: After processing element
i, the accumulator reflects the result of folding the reducer over elements[0..i].
Implementation (Python)
def reduce(collection, reducer_fn, initial_accumulator):
accumulator = initial_accumulator
for element in collection:
accumulator = reducer_fn(accumulator, element)
return accumulator
This implementation is eager: it processes all elements immediately. The reducer is applied sequentially, threading the accumulator through each step.
Part 2: Deriving Map and Filter
Map via Reduce
Map applies a transformation to each element, producing a new collection of the same length.
def map_via_reduce(collection, transform_fn):
def mapper_reducer(acc, element):
return acc + [transform_fn(element)]
return reduce(collection, mapper_reducer, [])
- Accumulator: An empty list, grown by appending each transformed element.
- Order preservation: Left-to-right iteration ensures output order matches input order.
- Performance note: List concatenation or append is typically O(1) amortized in Python, but immutable concatenation (
acc + [item]) creates a new list each time—O(n²) overall. A production implementation would use a mutable builder or explicit allocation.
Filter via Reduce
Filter keeps only elements satisfying a predicate.
def filter_via_reduce(collection, predicate_fn):
def filter_reducer(acc, element):
if predicate_fn(element):
return acc + [element]
return acc
return reduce(collection, filter_reducer, [])
- Accumulator: Starts empty, grows only when the predicate returns true.
- Order preservation: Matching elements appear in their original order.
- Performance: Same O(n²) caveat for repeated list concatenation.
Optimized Accumulators
To avoid quadratic behavior, use a mutable list and build once:
def map_via_reduce_optimized(collection, transform_fn):
def mapper_reducer(acc, element):
acc.append(transform_fn(element))
return acc
return reduce(collection, mapper_reducer, [])
This mutates the accumulator in place, reducing time complexity to O(n). The trade-off: less functional purity, but acceptable when the accumulator is newly allocated and never escapes mid-fold.
Part 3: Composition Example
Suppose we have a list of user records and want to extract ages of active users, incremented by one:
users = [
{"name": "Alice", "age": 30, "active": True},
{"name": "Bob", "age": 25, "active": False},
{"name": "Carol", "age": 35, "active": True},
]
active_users = filter_via_reduce(users, lambda u: u["active"])
ages_incremented = map_via_reduce(active_users, lambda u: u["age"] + 1)
print(ages_incremented) # [31, 36]
Composition Semantics
filterruns first, producing[{"name": "Alice", ...}, {"name": "Carol", ...}]mapthen transforms that intermediate result- Each operation is independent and uses only
reduceinternally - Order is preserved throughout the pipeline
Empty Input Handling
If users were empty, both operations return [] via their reduce calls with empty inputs.
Common Mistakes
- Forgetting the initial accumulator: Without it, reduce on an empty collection is undefined.
- Mutating the input: Map and filter should return new collections.
- Inefficient accumulators: Naive immutable concatenation causes O(n²) runtime.
- Wrong iteration order: Right-to-left reduce would reverse the output.
- Skipping empty-input tests: Edge cases often reveal off-by-one errors.
Complexity Analysis
- Time: O(n) for one reduce pass (assuming O(1) accumulator updates); O(n) for map, O(n) for filter.
- Space: O(n) for the output collection (unavoidable unless using lazy streams).
Callback Semantics Note (Python)
In Python, functions are first-class, and exceptions in callbacks propagate immediately, aborting the reduce. If side effects or shared mutable state are involved, order and exception safety matter.
This answer demonstrates the foundational nature of reduce, careful attention to accumulator design, and clean composition without resorting to separate iteration logic for each derived operation.