Skip to main content
3 of 5
Fixed typo
DJMcMayhem
  • 59.6k
  • 17
  • 196
  • 348

N(e(s(t))) a string

To "function nest" a string, you must:

  • Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

     H(ello)
    
  • Then, repeat this same step for every substring. So we get:

     H(ello)
     H(e(llo))
     H(e(l(lo)))
     H(e(l(l(o))))
    

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

H(e(l(l(o( (w(o(r(l(d(!)))))))))))

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses.

Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

DJMcMayhem
  • 59.6k
  • 17
  • 196
  • 348