R, 96 65 7272 69 bytes
Or R>=4.1, 6562 bytes by replacing the word function
with \
.
-many bytes by changing I/O to vector of char codes.
-another some bytes thanks to @Dominic van Essen.
+7 bytes costed converting from not-so-self-contained function to a program.
-3 bytes thanks to @Dominic van Essen - converting back to one (reusable) function.
i=0;s=scan`/`=function(s,t=0);f=function"if"((a=s[i<<-i+1]t*i+1])"if"(a<58<58,a,c(40,f()s/1,a,f()s/1,41));f();i=9
Port of @loopy walt's answer.
Explanation
Initiates global counterA function takes string is
toand 0t
and takes input withdefaulting to scan0
(for resetting global variable).
The recursive function (named f/
overriding division) takes one character at a time (a
) incrementing the global counter each time. If the character char code is less then 58, then it's a digit and needs to be returned as is. Otherwise, we surround the character with braces (char codes 40,41
) and recursive calls to our function (with t=1
to keep i
as is between calls).
The code at the end initiates global counter i
to a digit (9
chosen for demonstration purposes).
Solution shorter for R>=4.1:
R, 74 bytes
Or R>=4.1, 60 bytes by replacing two function
occurrences with \
s.
function(s,i=0,f=function(a=s[i<<-i+1])"if"(a<58,a,c(40,f(),a,f(),41)))f()
Same as above, but here i
is "local" for the main function, but "global" for the recursive one.