Functional folds in R: implement helpers with Reduce and Filter
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement four helper functions in R using base R's `Reduce` and `Filter`. Do not write explicit `for` or `while` loops.
- `fold_sum_squares(x)` returns the sum of squares of `x` as a numeric scalar, computed with `Reduce`. An empty vector returns `0`.
- `running_max(x)` returns a numeric vector of the same length as `x` whose i-th element is `max(x[1:i])`, computed with `Reduce(..., accumulate = TRUE)`. An empty vector returns `numeric(0)`.
- `filter_divisible(x, k)` returns the elements of `x` with `x %% k == 0`, in their original order, using `Filter`.
- `product_of_positives(x)` returns the product of the elements greater than 0, using `Filter` and then `Reduce`. If there are no positive elements, it returns `1`.
Example:
```r
fold_sum_squares(c(1, 2, 3)) # 14
running_max(c(3, 1, 4, 1, 5)) # 3 3 4 4 5
filter_divisible(c(1, 2, 3, 4, 5, 6), 2) # 2 4 6
product_of_positives(c(-2, 3, 4)) # 12
```
```hint Empty input
Check what `Reduce` returns for a zero-length vector when you pass no initial value. Then pick a starting value for each fold that leaves the result on a non-empty vector unchanged.
```
### What a Strong Answer Covers
- Every helper is built from `Reduce` and `Filter`, with no explicit loops.
- Each helper returns the required value on an empty vector, with the reason it does.
- How the `accumulate` mode of `Reduce` produces one value per prefix for the running maximum.
- Order preservation in the filter, and how zero and negative values are treated in the product.
- The time and space cost of each helper.
### Follow-up Questions
- Why pass an explicit initial value to `Reduce` for the sum and the product, and what changes if you also pass one to `running_max`?
- How would you generalize these into a single higher-order helper that takes a combiner, an initial value and an optional predicate?
- What do `NA` values and `k = 0` do in each helper, and what would you change?
- How do these versions compare in speed with vectorized base R such as `sum(x^2)`, `cummax(x)` and `prod(x[x > 0])`?
Overview: Implement four small R helpers with base R's Reduce and Filter and no explicit loops: a sum of squares, a running maximum, a divisibility filter and a product of positive values. It tests functional programming in R, initial values for empty input, and the accumulate option of Reduce.