R Expression to Prefix Notation and Call-Tree Depth
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Given a character scalar holding one valid R expression, implement two R functions that walk its parsed AST: one renders fully parenthesized prefix notation, the other returns the call-tree nesting depth. Grouping parentheses (the `(` call) are transparent in both: they add no token and no depth.
- `to_prefix(expr_str)` returns a length-1 character vector in prefix form.
- An atomic literal renders via `deparse()` (for example `"2"` or `"2.5"`), and a symbol renders as its text.
- A call `f(a, b, ...)` becomes `"(f pre(a) pre(b) ...)"` with single-space separators, function or operator name first.
- `expr_depth(expr_str)` returns a length-1 integer-valued numeric: the maximum call-tree depth.
- An atom or symbol has depth `0`, and a call has depth `1 + max(depth of its arguments)`.
Example:
```r
to_prefix("1 + 2") # "(+ 1 2)"
to_prefix("a * (b + c)") # "(* a (+ b c))"
to_prefix("f(x, y, z)") # "(f x y z)"
expr_depth("1") # 0
expr_depth("1 + 2 * 3") # 2
```
```hint Let R do the parsing
You do not need a tokenizer. Look for a base R function that turns a string into a language object, then check how a call node stores its function and its arguments.
```
```hint Where grouping hides
Run `as.list(quote((b + c)))` and see how the parentheses show up in the tree. Both functions have to step past that node.
```
### What a Strong Answer Covers
- Parses the string with R's own parser and recurses over the resulting call, symbol and literal nodes.
- Treats every call the same way (head first, then each argument), so infix operators, unary operators and ordinary function calls all follow one rule.
- Skips the `(` grouping call in both functions so it adds no token and no depth.
- Gets the base cases right: symbols as their text, literals through `deparse()`, and a call with no arguments in the depth function.
- States the time and space cost in terms of the number of nodes and the nesting depth.
### Follow-up Questions
- How would you handle unary operators like `-x` or `!flag`?
- How would you extend this to a whole program with multiple statements?
- `round(x, digits = 2)` renders as `"(round x 2)"` and loses the argument name. How would you keep names in the output?
Overview: Parse a string holding one R expression, then walk its syntax tree to print fully parenthesized prefix notation and to compute how deeply its calls nest. It tests recursion over R language objects, uniform handling of operators as calls, and careful base cases such as grouping parentheses.