Catch warnings and errors in R with tryCatch and return a fallback value
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement two R functions that use `tryCatch`, with both a `warning =` and an `error =` handler, to evaluate a function safely. When `f(x)` signals a warning or an error, catch it and return a fallback value so the condition does not propagate to the caller.
- `safe_compute(f, x, fallback = NA_real_)` calls `f(x)` and returns a named list with exactly three elements: `value`, `status` and `message`.
- On success, `value` is `f(x)`, `status` is `"success"` and `message` is `NA_character_`.
- When a warning or an error is caught, `value` is `fallback` and `status` is `"warning"` or `"error"`.
- For warnings and errors, `message` is `conditionMessage()` of the caught condition.
- `safe_map(f, xs, fallback = NA_real_)` returns a numeric vector of length `length(xs)` whose element `i` is `safe_compute(f, xs[i], fallback)$value`. You may assume `f` returns a numeric scalar on success.
Example:
```r
safe_compute(sqrt, 4)
# $value = 2, $status = "success", $message = NA_character_
safe_compute(function(x) log(x), -1)
# $value = NA_real_, $status = "warning", $message = "NaNs produced"
safe_compute(function(x) stop("boom"), 1)
# $value = NA_real_, $status = "error", $message = "boom"
safe_map(sqrt, c(4, 9, 16))
# c(2, 3, 4)
```
```hint Where the success list is built
Decide where the success list gets built so that `f(x)` runs exactly once, whatever happens.
```
```hint The mapped result type
For `safe_map`, pick an apply function that checks every result is a single number and still returns a numeric vector when `xs` is empty.
```
### What a Strong Answer Covers
- One `tryCatch` with separate `warning` and `error` handlers, each returning the full three-element list.
- How many times `f(x)` is evaluated, and why that matters for side effects and for conditions.
- What a `warning` handler in `tryCatch` does to the evaluation of `f(x)` and to its value.
- A `safe_map` that returns a numeric vector of the right length, including for empty input, with a type check on each element.
### Follow-up Questions
- How would you distinguish a warning where `f(x)` still produced a usable value from one where it didn't?
- How would you make `safe_map` efficient over a large `xs`?
- Which conditions does this code leave uncaught, and should it catch them?
Overview: Write two R functions that call another function safely with tryCatch, returning a fallback value with a status and a message when a warning or an error occurs, and then map that safe call over a vector. It tests R's condition handling, exiting handlers and type-checked apply functions.