# 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, and will not be empty.

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))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)


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

• Ahem: Is this message anything to do with the challenge? :-) Oct 18, 2016 at 18:46
• T​I​L 4​2​ ​= 8 Oct 18, 2016 at 21:48
• What is maximum length for the input string? Incase of recursive methods Oct 23, 2016 at 20:30
• @kamoroso94 You may take the input and the output in any reasonable format. A list of characters seems perfectly reasonable to me. Sep 1, 2017 at 15:29
• So that's what Lisp code looks like Dec 17, 2017 at 18:35

# Brachylog, 3528 25 bytes

l-L,")":LjkC,?:"("zckc:Cc


Try it online!

Explanation

l-L,          # L is length of input - 1
")":LjkC,     # C is ")" repeated L-1 times
# output is
?:"("z        # input zipped with "("
ckc     # flattened to a string with the last element removed
:Cc  # concatenated with C


# Factor, 81 bytes

[ [ >array [ 1string ] map "("join ] [ length 1 - [ 40 ] replicate >string ] bi ]


# Java 82 81

Thanks to Olivier Grégoire for the correction leading to 1byte less.

# Solution

I forced myself in using a String a not a char[] so this is a bit more verbose :/

String n(String s){return s.length()>1?s.charAt(0)+"("+n(s.substring(1))+")":s;}


A simple recursive function.

# Test

public static void main(String[] a){
System.out.println(n("test"));
System.out.println(n("Hello world!"));
}


t(e(s(t)))

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

• For Java 7, did you notice that the last character is duplicated? For Java 8, it won't compile and work because you have to define a recursive function like this: n=s->...n.apply(...) instead of s->...n(...), also there are some other issues which make your answer don't work. Oct 21, 2016 at 9:30
• Thanks, indeed I missed that ... I just made the correction and gain a byte, thanks :) . I removed the Java 8 part since I can't test it here and don't have enought experience to do it blindly ;) Oct 21, 2016 at 9:45
• Well, actually a recursive function can't work in Java 8. You always get a "self-reference in intializer" error. Oct 21, 2016 at 9:55
• @OlivierGrégoire Never used Lambda for complex code, mainly for small validation process. But thanks for the info, I will dig into this. Oct 21, 2016 at 9:56

# Dyalog APL, 14 bytes

⊃{⍺,1⌽')(',⍵}/

this is an atop of ⊃ and { }/

⊃ (get first element) will be applied after { }/ (reduction of a lambda)

⍺,1⌽')(',⍵ - the left argument (⍺) concatenated with (,) the rotation by one element to the left (1⌽) of the string ')(' concatenated with (,) the right argument (⍵)

reduction in APL folds from right to left, as required here

# Stax, 8 6 bytes

-2 thanks to @recursive!

çΔ \Γ]


Run and debug it at staxlang.xyz!

### Unpacked (7 bytes) and explanation:

Mrks:{+
M          Transpose array. This turns a string into an array of length-1 strings.
r         Reverse string.
k        Fold array using the rest of the program as a block:
s         Swap. This puts the accumulator on top of the current element.
:{       Wrap in parentheses.
+      Concatenate.
Implicit print at end of program!

• If you transpose the input string, you can get rid of the stringifications, and pack down to 6. Mrks:{+ May 24, 2018 at 17:03
• @recursive Ah. That's what I was looking for. Definitely beats {]m for the same functionality! May 25, 2018 at 19:57

# Perl 5, 44 33 bytes (31 + 1 for -l + 1 for -p)

saved 11 bytes thanks to Dada

s/([\w ])([\w ]+)/$1($2)/&&redo


Can be run from the command line with the -p and -e options.

$perl -ple 's/([\w ])([\w ]+)/$1($2)/&&redo' <<< 'Hello'  Output: H(e(l(l(o))))  • You can use -l instead of chomp to save 5 bytes. Also, since -p surround the code with a while, you can do s/../../&&redo instead of 0while s/../../. As it happens, this regex is shorter : s/([\w ])([\w ]+)/$1($2)/. – Dada Oct 18, 2016 at 20:38 • Another thing : usually, when you really need to chomp, you can chop instead to save one byte ;) – Dada Oct 18, 2016 at 20:49 • @Dada thanks, didn't think about the redo and got caught up building a complicated regex. I need to understand that golf is not obfuscation. ;) Oct 18, 2016 at 21:06 • You code wasn't that bad! It just takes time and practice! And even after that, Ton Hospel will always find a shorter way than everybody else! ;-) – Dada Oct 18, 2016 at 21:16 • You are supposed to support all printable ASCII so you need [^()] instead of [\w ]. The first one in fact only needs [^(] Oct 19, 2016 at 5:09 # C, 102 89 bytes Maybe this can be golfed more? I'm just happy to answer in C! :D i=0,j=0;f(char*a){while(*a)putchar(*a),*++a?putchar(40),i++:0;while(j<i)putchar(41),j++;}  • 79 bytes Oct 17, 2019 at 20:31 • @ceilingcat braver than me. – cat Oct 18, 2019 at 4:58 # SWI-Prolog, 82 bytes q([H],[H]). q([H|T],[H,40|S]):-q(T,R),append(R,[41],S). X*Y:-q(X,Z),atom_codes(Y,Z).  Called like: Hello World!*X. Online interpreter • Worth mentioning that this is shorter but can't handle symbols correctly. Jan 25, 2021 at 23:57 # k, 16 bytes This is an anonymous function composition {y,"(",x,")"}/|:  Example k){y,"(",x,")"}/|:"hello world" "h(e(l(l(o( (w(o(r(l(d))))))))))"  ## Mathematica, 35 27 bytes bytes Saved 8 bytes on adding the appropriate number of ")" to the end thanks to alephalpha #~Riffle~"("<>Most[0#+")"]&  Input is a list of characters. Riffles "(" between each character, then adds that many ")" minus 1 to the end. Specifically, multiplies the input by 0, adds ")" and then takes Most of the list. e.g. #~Riffle~"("<>Most[0#+")"]&[{"H","e","l","l","o"}] {"H","e","l","l","o"}~Riffle~"("<>Most[0{"H","e","l","l","o"}+")"] {"H","(","e","(","l","(","l","(","o"}<>Most[{0,0,0,0,0}+")"] {"H","(","e","(","l","(","l","(","o"}<>Most[{")",")",")",")",")"}] {"H","(","e","(","l","(","l","(","o"}<>{")",")",")",")"} "H(e(l(l(o))))"  • #~Riffle~"("<>Most[0#+")"]& Jan 11, 2017 at 14:30 # Brain-Flak, 118 84 + 1 = 85 bytes Try it online ([[]]<{({}<>)((((()()()()()){}){}){})<>}>()){({}()<(<>({})<>())>)}{}<>{}{({}<>)<>}<>  This requires the -fc flag to run giving it an extra byte. -f flag is standard for passing input. ## Explanation ([[]]< #Store a copy of the stack height before hand in the scope { #While there is something on the stack... ({}<>) #Move something over and... ((((()()()()()){}){}){}) #Put a paren on top <> #Swap back } >()) #Put the 1-stack height down { #While that is not zero ({}()< #Add one and (<>({})<>())#Silently move a copy of the top of the other stack over (close paren) >) }{} <>{} #Remove extra open paren {({}<>)<>}<> #Combine the two stacks  # Poetic, 244 bytes life is a quest,i say i choose a fun course to cross i cant say quite if survival excites i say i am laughing i create a way i relive a feeling exile is torture,i say i am thankful,of course,to say i adore u i desire a wedding where i said i do  Try it online! Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols. The point of the language is to allow for programs to be written in free-verse poetry. # 05AB1E, 11 10 bytes -1 byte thanks to @Kevin Cruijssen S'(ý?¨v')?  Try it online! ## Explanation  #implicit input S #cast input to list ý #list join '( #( character ? #print list without a newline v #foreach item in ¨ #first input[0:-1] ')? #print ) without a newline  • Welcome to the site! Dec 25, 2019 at 0:24 • thank you! @WheatWizard Dec 25, 2019 at 1:23 • You can remove the ¹ to save a byte. It will use the input implicitly again, since the stack is empty. :) Jan 3, 2020 at 9:12 # Vyxal, 7 bytes ÷!‹(øb+  Try it Online! ÷ # Push each to the stack !‹( # (input-1) times... øb # Parenthesise what's currently on the stack + # and append it  • gamed on Nov 2, 2021 at 12:27 • @lyxal Not anymore ;) Jun 11, 2022 at 6:02 # Lua, 88 bytes Probably not nearly as short as it could be. x=""y=...for i=1,#y-1 do x=x..y:sub(i,i).."("end print(x..y:sub(-1,-1)..(")"):rep(#y-1))  Takes input from the command line. • Here's even better! y=...print(y:gsub('.','%1(',#y-1)..(')'):rep(#y-1)) 51 bytes I also made variations for repeat until and while end but they were longer than yours even though as minified as possible. – ascx Oct 20, 2016 at 12:38 • @ascx In here, you're not allowed to edit his answer just to golf it further. Let the author did that. Oct 23, 2016 at 14:33 • Oct 23, 2016 at 14:35 # Pyth - 9 bytes +j$$Qsm$$  • The output has one ) too many. Oct 19, 2016 at 11:40 • Use +j$$Qstm$$ instead. Oct 19, 2016 at 12:27 ## Ruby, 41 29 bytes ->s{s.split("").join(?()+?)*(s.length-1)} ->s{(s.chars*?()+?)*~-s.size}  Thanks @ValueInk • chars is more efficient than split, and I believe you want s.length-1 Oct 18, 2016 at 19:16 • size is more efficient than length, and multiplying an array by a string does an implicit join. And finally, (x-1) can be substituted to ~-x. Combining with Lee W suggestions, you end up with ->s{(s.chars*?()+?)*~-s.size} for 29 bytes! Oct 19, 2016 at 0:36 • And then I realize that these standard optimizations causes it to be exactly like @m-chrzan's answer, and now this is a tad awkward Oct 19, 2016 at 0:38 # Turtlèd, 25 27 bytes (original didn't work for single char inputs ;_;) This is what Turtlèd ended up being for even though it as originally ascii art stuff. !-l[*+.r'(r_]l-_[*-')r_]" [2 trailing spaces]  ### Try it online! ## Explanation: put the input on to the cells with ( after each char ! Take a string as input - decrement the string pointer, so it points at last char l move left [* ] while the current cell is not * +.r increment string pointer and write the pointed char, move right '(r write (, move right _ write * if pointed char is last char, else " " Write the terminating parens, the first one overwriting the last open paren l- move left, decrement string pointer _ write * if pointed char is last char, else " " [* ] while the current cell is not * -')r decrement string pointer, write ), move right _ write * if pointed char is last char, else " " "[2 spaces] Remove the last *, or two *s if input is one char  # Zsh, 36 Bytes z=${1:1};<<<${1[1]}${z///(}${z//?/)}  This should be possible in 34 bytes, but zsh syntax is inconsistent. $a[1] will return the first character of the string $a, but $1[1] returns the entire contents of $1 plus the string "[1]". I'd love to know if this is intended behavior, or just on a long list of zsh documentation not covering edge cases. The logic used is 1. Assign all but the first character of the first argument to a variable z 2. Print the first character of the input 3. Print z, with "the empty string replaced with (" which actually places a ( before each character of z 4. Print z, with all of the characters replaced with ) I don't think its golfable much farther from here, even though I how many characters it takes to just split the first character from the rest of the string. There is probably a more efficient "logic" though, I just couldn't find one that synergizes with zsh or bash. Speaking of bash, this doesn't work because the cute trick with sed-style replacing the empty string does not do anything in bash. I will edit with a solution that is better designed for bash-compatible syntax. • Really cool solution but doesn't handle the single-character input properly. Adjusted solution for 55 bytes. z=${1:1};(($#1==1))&&<<<$1||<<<${1[1]}${z///(}${z//?/)} Oct 27, 2021 at 4:41 ## Mathematica, 45 43 bytes #2<>"("<>#<>")"&~Fold~Reverse@Characters@#&  • You can use # instead of #1. And infix notation ~Fold~ should also work. Oct 19, 2016 at 8:42 # Bash / sed, 74 bytes y=$(echo $1|sed "s/./\0(/g");z=$(echo $1|sed "s/./)/g");echo${y%?}${z%?}  • Puts a parenthesis after each characters in y. • Puts a parenthesis for each characters in z. • Print x and z truncated of one character. To test, put this code into a file, and run the shell script with any arguments. # Pyth, 10 characters +j$$Q*$$tl  Try it online! Joins the input on (, and appends length - 1 closing parens afterwards. # CJam, 12 11 bytes One byte saved by Martin Ender. q_'(*\,(')*  Try it online • You can save a byte by avoiding the second \: q_'(*\,(')* Oct 21, 2016 at 12:01 Scala, 58 bytes "Hello world!"match{case s =>s.mkString("(")+")"*s.length}  Could be shorter • I think you meant (s:String)=>s.mkString("(")+")"*s.length (40 bytes) (no need for match case here) May 28, 2018 at 7:22 • Also - I think it's not correct. You'll need *(s.length-1) May 28, 2018 at 7:26 # Actually, 10 bytes lD')*ß'(j+  Try it online! Explanation: lD')*ß'(j+ lD')* ")"*(len(input)-1) ß'(j insert a "(" between every pair of characters in the input + append the closing parens  # V, 9 bytes $òys$)hhl  Try it online! # JavaScript, 36 bytes ([...v])=>v.join(+v.fill.join)  I can't seem to beat the top score of 34 bytes, but I thought I would share my different approach. • Apparently OP allowed (in his comments in 2017) list/array of characters as input. So your answer could be 29 bytes ? Mar 10 at 10:43 # PHP, 516068 63 bytes Why not just do what´s asked for instead of emulating it? Recurse! function n($s){return$s[1]>""?"$s[0](".n(substr($s,1)).")":$s;}

• why not change $s[1]>"" into just $s[1]? 3 chars less.
– nl-x
Oct 24, 2016 at 13:40
• @nl-x because the 0 character evaluates to false Oct 24, 2016 at 13:43
• @nl-x ... but I learned something just as long in the meantime. Mar 7, 2017 at 23:53
• Please do explain what you did there...
– nl-x
Mar 8, 2017 at 7:26
• @nl-x I messed it up. I intended a shorter check on the second character using bitwise arithmetics, but checked the string for emptiness instead. Rolled back. Mar 8, 2017 at 13:02

## QBIC, 64 bytes

Way too large. Posted as an incentive to get my butt moving again on the QBIC project.

;_LA|[a-1|Z=Z+$mid$|(A,b,1)+@(|]Z=Z+$right$|(A,1)[a-1|Z=Z+@)|]?Z


All those $mid$| and $right$|s should be turned into QBIC commands, but to do that I first need to solve a problem with nesting function calls...

EDIT: Got my butt moving. Now in 48 bytes:

_L;|[a-1|Z=Z+_sA,b,1|+@(]Z=Z+_sA,-1|[a-1|Z=Z+@)

• Huh. QBIC looks interesting. Is there a github project I could follow? Or a README describing what it is? Nov 28, 2016 at 18:11
• @DrMcMoylex I swear, the day I figure out how Github works ... The project lives in a shared folder on a Google Drive, link in the header. Some info o getting started here and here. Nov 28, 2016 at 18:23
• Why is QBIC not on TIO? Nov 10, 2017 at 18:36
• @MDXF Well, QBIC code is converted into QBasic code, which is run in Dosbox. I do not believe that such an environment can be easily set up for use on the web... I am taking suggestions however :) Nov 10, 2017 at 20:19
• @steenbergh Ah, that's true. I'm actually looking into ways to get QBasic / ABASIC / Applesoft Basic onto TIO. Right now it's looking like I'm going to need to write my own interpreters. >.< Nov 11, 2017 at 4:55

# R, 56 bytes

function(s)c(paste(s,collapse="("),rep(")",length(s)-1))


Try it online!

Plain old R. Recursive solution below. Both input and output are vectors of characters.

### R, 57 bytes

f=function(s)"if"(length(s)>1,c(s[1],"(",f(s[-1]),")"),s)
`

Try it online!