# 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

# Python, 4139 34 bytes

lambda e:"(".join(e)+")"*~-len(e)


Ideone it

Pretty self explanatory.

It puts a parenthesis between every other character then adds one less than the length parentheses to the end.

• That ~- trick is cool, I will need to remember that. Oct 18, 2016 at 19:25
• how does the ~-trick work ? Oct 19, 2016 at 14:08
• @ShadowFlame - makes the number negative and ~ bit flips it. You can read a bit more about it on the tips page. Oct 19, 2016 at 14:11
• @ShadowFlame. The mechanics of it is as WheatWidard said. It works on systems that use twos-complement mode to store negative numbers (which is most systems nowadays). Oct 21, 2016 at 17:40
• @MadPhysicist With Python, it works always, because ~ is defined as -x-1 May 28, 2018 at 12:51

## MS-DOS .com file, 30 bytes

0000   fc be 82 00 b4 02 ac 88 c2 cd 21 ac 3c 0d 74 0d
0010   b2 28 50 cd 21 5a e8 f0 ff b2 29 cd 21 c3


The string is passed to the executable using the command line. (One space character between the .COM file name and the string).

The result is written to standard output.

The disassembly is here:

  fc          cld              ; Make sure DF is not set (lodsb!)
be 82 00    mov    si,0x82   ; First character of command line args
b4 02       mov    ah,0x2    ; AH=2 means output for INT 21h
ac          lodsb            ; Load first character
88 c2       mov    dl,al     ; Move AL to DL (DL is written to output)
recursiveFunction:
cd 21       int    0x21      ; Output
ac          lodsb            ; Get the next character
3c 0d       cmp    al,0xd    ; If it is "CR" (end of command line) ...
74 0d       je     doReturn  ; ... return from the recursive function
b2 28       mov    dl,0x28   ; Output "(" next...
50          push   ax        ; ... but save character read first
cd 21       int    0x21      ; (Actual output)
5a          pop    dx        ; Restore character (but in DL, not in AL)
e8 f0 ff    call   recursiveFunction  ; Recursively enter the function
doReturn:
b2 29       mov    dl,0x29   ; Output ")"
cd 21       int    0x21
c3          ret              ; Actually return


Note: You can exit a DOS .COM file (unlike files with EXE headers) using a "RET" instruction.

• Since I can't find any actual documentation or satisfactory info: why call 0xfoff? The program is loaded into memory at address 0 as far as I can tell (or 0x100 on CP/M-DOS but these appear to be x86 instructions), why is recursiveFunction suddenly located at 0xffof? It appears to begin 9 bytes after the beginning of the program, and there is no virtualisation or metadata in the executable.
– cat
Oct 20, 2016 at 23:19
• DOS loads .COM files to address 0x100 however this program would even run on ANY address: e8 f0 ff is a relative call instruction: It jumps to the address of the instruction following the call instruction minus 0x10. Oct 21, 2016 at 5:59

## JavaScript (ES6), 4034 33 bytes

Saved 6 bytes, thanks to ETHproductions

A recursive function.

f=([c,...s])=>s+s?c+(${f(s)}):c  Try it online! • Nice trick with 1/s. Oct 18, 2016 at 19:38 • Super nice trick with ([c,...s]) you should write a tip Oct 18, 2016 at 21:27 • @edc65 Just for sake of clarity, this one was suggested by ETHproductions. Oct 18, 2016 at 21:40 • o well, someone has to write a tip anyway Oct 18, 2016 at 21:42 • @jmingov thank you, I know. The point here is using DA to to slice a string in a very short way (very shorter than .slice) Oct 19, 2016 at 7:16 # Brainfuck, 42 40 bytes >+[-->+[<]>-]>+>>,.,[<+<.>>.,]<<+>[-<.>]  Try it online! Ungolfed: >+[-->+[<]>-]>+ # count to 40 (ASCII for open paren) >> # move to the input holder ,. # input the first byte and output it , # input the next byte [ # while it's not zero <+ # move to the input counter and increment it <. # move to the open paren and output it >>. # move to the input holder and output it , # input the next byte ] <<+ # move to the open paren and increment it to a close > # move to the input counter [ # while it's not zero - # decrement it <. # move to the close paren and output it > # move to the input counter ]  • There is usually a shorter way to get a constant than the obvious 2-factor multiplication. Oct 18, 2016 at 20:16 • Ah nice, thanks. This was my first BF submission (my first BF program at all, really) so I'm sure there are lots of other possible improvements too. Oct 18, 2016 at 20:58 • you got one pair of brackets to much!? Oct 21, 2016 at 14:04 • This puts an empty pair of parentheses after the last character of the string. I don't know if there's a way to avoid that without adding ",." before the loop and switching the output order inside the loop, which makes the program two bytes longer. Oct 21, 2016 at 22:34 • Ah bugger, you're right. I didn't read carefully enough and made the last letter a function call like the others. Oct 23, 2016 at 17:54 # 05AB1E, 11 bytes S'(ý¹g<')×J  Try it online! Explanation: S'(ý join input by "(" ¹g< push length of input - 1, call it n ')× push a string with char ")" n times J concatenate  # Brainfuck, 44 bytes >+++++[-<++++++++>],.,[<.>.>+<,]<+>>[-<<.>>]  Reads a byte at a time, puts an open-paren before each one except the first, puts the same number of close-parens at the end. • +++++[->++++++++<],.,[>.>+<<.,]>+>[-<.>] is slightly shorter. Oct 18, 2019 at 4:48 ## Haskell, 30 bytes f[x]=[x] f(a:b)=a:'(':f b++")"  Usage example: f "Nest a string" -> "N(e(s(t( (a( (s(t(r(i(n(g))))))))))))". Take the next char, followed by a (, followed by a recursive call with all but the first char, followed by a ). • If we interpret the answers as Haskell, we can solve it with just f=Data.List.intersperse '$'! That gives us f "Nest a string" -> "N$e$s$t$ $a$ $s$t$r$i$n$g". Oct 19, 2016 at 1:02
• Just wanted to let you know that @fornit (he hasn't enough rep to comment) suggested to use f[]=[] as a base case instaed of your f[x]=[x]. I'm not familiar with Haskell so I don't know whether it's legit or not, I'll let you judge.
Oct 24, 2016 at 13:13
• @Dada: that won't work, because it would put an additional () behind the last letter, e.g. f "abc" -> "a(b(c()))".
– nimi
Oct 24, 2016 at 15:52
• This also doesn’t handle empty input. The shortest correct version I could come up with is 44, with a different technique: f=(++).intersperse '('<*>drop 1.map(\_->')'). Oct 27, 2016 at 3:48
• @JonPurdy: we don't have to handle empty input. intersperse requires import Data.List for another 17 bytes.
– nimi
Oct 27, 2016 at 9:15

# Jelly, 9 8 bytes

-1 byte thanks to @Dennis (use mould, ṁ, in place of length, L, and repeat, x)

j”(³”)ṁṖ


TryItOnline

### How?

j”(³”)ṁṖ - Main link: s     e.g. "code-golf"           printed output:
j        - join s with
”(      - literal '('           "c(o(d(e(-(g(o(l(f"
”)   - literal ')'
ṁ  - mould like
³     - first input, s        ")))))))))"
- causes print with no newline of z:          c(o(d(e(-(g(o(l(f
Ṗ - pop (z[:-1])          "))))))))"            c(o(d(e(-(g(o(l(f
- implicit print                              c(o(d(e(-(g(o(l(f))))))))

• Btw, ³ actually causes Jelly to print the current return value, so you never have two lists of chars. Oct 18, 2016 at 21:09
• Alternate 8 byter Nov 2, 2021 at 12:36
• @lyxal Nice. I don't think Ø( existed back then. Nov 2, 2021 at 22:51

## Retina, 22 17 bytes

\1>.
($& T(p)_  Try it online! Alternatively: S_ \¶ ( T(p)_  ### Explanation I always forget that it's possible to print stuff along the way instead of transforming everything into the final result and outputting it in one go... \1>. ($&


Here \ tells Retina to print the result of this stage without a trailing linefeed. The 1> is a limit which means that the first match of the regex should be ignored. As for the stage itself, it simply replaces each character (.) except the first with ( followed by that character. In other words, it inserts ( in between each pair of characters. For input abc, this transforms it into (and prints)

a(b(c


All that's left is to print the closing parentheses:

T(p)_


This is done with a transliteration which replaces ( with ) and deletes all other printable ASCII characters from the string.

• Dangit. So fast... Oct 18, 2016 at 18:43
• @mbomb007 ...and far from optimal. ;) Oct 18, 2016 at 19:05

# J, 13 bytes

(,'(',,&')')/


J executes from right-to-left so using the insert adverb /, a verb can be used to reduce the letters of the input string.

## Usage

   f =: (,'(',,&')')/
f 'Nest a string'
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))
f 'foobar'
f(o(o(b(a(r)))))
f '1234567890'
1(2(3(4(5(6(7(8(9(0)))))))))
f 'code-golf'
c(o(d(e(-(g(o(l(f))))))))


You can observe the partial outputs between each reduction.

   |. f\. 'Hello'
o
l(o)
l(l(o))
e(l(l(o)))
H(e(l(l(o))))


## Explanation

(,'(',,&')')/  Input: string S
(          )/  Insert this verb between each char and execute (right-to-left)
,&')'      Append a ')' to the right char
'(',           Prepend a '(' to that
,               Append to the left char


## ><>, 19 18 bytes

io8i:&0(.')('o&!
o


Try it online!

### Explanation

The first line is an input loop which prints everything up to the last character of the input (including all the () and leaves the right amount of ) on the stack:

io                 Read and print the first character.
8                Push an 8 (the x-coordinate of the . in the program).
i               Read a character. Pushes -1 at EOF.
:&             Put a copy in the register.
0(           Check if negative. Gives 1 at EOF, 0 otherwise.
.          Jump to (8, EOF?). As long as we're not at EOF, this is
a no-op (apart from popping the two coordinates). At EOF
it takes us to the second line.
')('      Push both characters.
o     Output the '('.
&    Push the input character from the register.
!   Skip the 'i' at the beginning of the line, so that the next
iteration starts with 'o', printing the last character.


Once we hit EOF, the instruction pointer ends up on the second line and we'll simply execute o in a loop, printing all the ), until the stack is empty and the program errors out.

# C#, 32 bytes

F=s=>*s+++(0<*s?$"({F(s)})":"");  This lambda must be a static method, would I need to count any extra bytes for that requirement? Normally I wouldn't use a lambda for recursion in C#, but then I think it would be shorter not to use recursion. /*unsafe delegate string Function(char* s);*/ // Lambda signature /*static unsafe Function*/ F = s => *s++ // Take first char and increment pointer to next one + (0 < *s // Check if any chars left ?$"({F(s)})"                  // If so concat surrounding parens around recursion
: ""                           // Otherwise done
)
;

• the definition should run as declared and counted
– cat
Oct 22, 2016 at 11:25

# Java 7,81 79 bytes

Saved 1 byte.Thanks to kevin.

String f(char[]a,String b,int l){return l<a.length?f(a,b+'('+a[l],++l)+')':b;}

• Nice recursive approach. Shorter than the for-loop I was about to post. +1 Two things you can golf though: l!=a.length -> l<a.length and b=b+'('+a[l],++l)+')' -> b+="("+a[l],++l)+")" (-2 bytes) Oct 19, 2016 at 7:58
• @KevinCruijssen b+="("+a[l],++l)+")" gives you 144141148))),and BTW b+"("+a[l],++l)+")" is correct. and this was very silly mistake of mine(!=). Oct 19, 2016 at 14:22
• No, b+='('+a[l],++l)+')' gives 144141148, but b+="("+a[l],++l)+")" doesn't. The parentheses are surrounded by String-quotes instead of char-quotes. Oct 19, 2016 at 19:06
• I post my version (82 bytes in Java 7) using only the input String as parameter. Verbose but not that bad ;) If you find something to change : codegolf.stackexchange.com/a/96745/59739 Oct 20, 2016 at 14:10

# R, 61 bytes

cat(gsub("(?<=.)(?=.)","(",x,F,T),rep(")",nchar(x)-1),sep="")


Regex finds and replaces spaces between characters with "(". Then cat and rep add ")" n-1 times at the end.

• Can actually subtract 1 byte here by eliminating the F, like so, this is because each entry already has a default setting, so leaving an empty character between commas will cause the ignore.case option to use its default. But you likely knew that... Job well done! Aug 28, 2018 at 13:29

## PowerShell v2+, 46 bytes

param([char[]]$a)($a-join'(')+')'*($a.count-1)  Takes input string, char-array's it, -joins the array together with open parens (, then concatenates on the appropriate number of closed parens ). # APL, 19 bytes {∊('(',¨⍵),')'⍴⍨⍴⍵}  Explanation: { ('(',¨⍵) ⍝ join a ( to each character in ⍵ ,')'⍴⍨⍴⍵ ⍝ for each character in ⍵, add an ) to the end ∊ ⍝ flatten the list }  Alternative solution, also 19 bytes: {⊃{∊'('⍺⍵')'}/⍵,⊂⍬}  Explanation: { ⍵,⊂⍬ ⍝ add an empty list behind ⍵ (as a base case) { }/ ⍝ reduce with this function: '('⍺⍵')' ⍝ put braces around input ∊ ⍝ flatten the list ⊃ ⍝ take first item from resulting list }  • Where do you buy the keyboards for such a language!!! Oct 19, 2016 at 13:13 • @RonanDejhero Perhaps just remapping keys using cltr, shift, alt, capslock, numlock etc. Oct 27, 2016 at 5:04 • It can be shortened using trains, I guess: (∊'('∘,¨,')'⍴⍨⍴) But doesn't this add an extra couple of brackets? Dec 24, 2019 at 12:02 • Both solutions and also the one suggested by @Popov put an extra set of brackets around the output required in the question. Nov 2, 2021 at 20:19 # MATL, 16 bytes t~40+v3L)7MQ3L)h  Try it online! ### Explanation t % Implicit input. Duplicate % STACK: 'foobar', 'foobar' ~ % Negate. Transforms into an array of zeros % STACK: 'foobar', [0 0 0 0 0 0] 40+ % Add 40, element-wise. Gives array containing 40 repeated % STACK: 'foobar', [40 40 40 40 40 40] v % Concatenate vertically. Gives a two-row char array, with 40 cast into '(' % STACK: ['foobar'; '(((((('] 3L) % Remove last element. Converts to row vector % STACK: 'f(o(o(b(a(r' 7M % Push array containing 40 again % STACK: 'f(o(o(b(a(r', [40 40 40 40 40 40] Q % Add 1, element-wise % STACK: 'f(o(o(b(a(r', [41 41 41 41 41 41] h % Concatenate horizontally, with 41 cast into ')' % STACK: 'f(o(o(b(a(r)))))' % Implicit display  ## Acc!!, 129 bytes Not bad for a fairly verbose Turing tarpit... N Count i while _%128-9 { Count x while _/128%2 { Write 40 _+128 } Write _%128 _+128-_%128+N } Count j while _/256-j { Write 41 }  (Yes, all that whitespace is mandatory.) Note: because of the input limitations of Acc!!, it is impossible to read an arbitrary string of characters without some ending delimiter. Therefore, this program expects input (on stdin) as a string followed by a tab character. ### Acc!!? It's a language I created that only appears to be unusable. The only data type is integers, the only control flow construct is the Count x while y loop, and the only way to store data is a single accumulator _. Input and output are done one character at a time, using the special value N and the Write statement. Despite these limitations, I'm quite sure that Acc!! is Turing-complete. ### Explanation The basic strategy in Acc!! programming is to use mod % and integer division / to conceptually partition the accumulator, allowing it to store multiple values at once. In this program, we use three such sections: the lowest-order seven bits (_%128) store an ASCII code from input; the next bit (_/128%2) stores a flag value; and the remaining bits (_/256) count the number of close-parens we will need. Input in Acc!! comes from the special value N, which reads a single character and evaluates to its ASCII code. Any statement that consists solely of an expression assigns the result of that expression to the accumulator. So we start by storing the first character's code in the accumulator. _%128 will store the most recently read character. So the first loop runs while _%128-9 is nonzero--that is, until the current character is a tab. Inside the loop, we want to print ( unless we're on the first iteration. Since Acc!! has no if statement, we have to use loops for conditionals. We use the 128's bit of the accumulator, _/128%2, as a flag value. On the first pass, the only thing in the accumulator is an ASCII value < 128, so the flag is 0 and the loop is skipped. On every subsequent pass, we will make sure the flag is 1. Inside the Count x loop (whenever the flag is 1), we write an open paren (ASCII 40) and add 128 to the accumulator, thereby setting the flag to 0 and exiting the loop. This also happens to increment the value of _/256, which we will use as our tally of close-parens to be output. Regardless of the flag's value, we write the most recent input char, which is simply _%128. The next assignment (_+128-_%128+N) does two things. First, by adding 128, it sets the flag for the next time through the loop. Second, it zeros out the _%128 slot, reads another character, and stores it there. Then we loop. When the Count i loop exits, we have just read a tab character, and the accumulator value breaks down like this: • _%128: 9 (the tab character) • _/128%2: 1 (the flag) • _/256: number of characters read, minus 1 (The minus 1 is because we only add 128 to the accumulator once during the first pass through the main loop.) All that we need now are the close-parens. Count j while _/256-j loops _/256 times, writing a close-paren (ASCII 41) each time. Voila! # Ruby, 27 bytes ->s{s.chars*?(+?)*~-s.size}  ## Explanation ->s{ # Declare anonymous lambda taking argument s s.chars # Get the array of chars representing s *?( # Join the elements back into a string using "("s as separators +?)*~-s.size # Append (s.size - 1) ")"s to the end  # Perl, 24 23 bytes Includes +1 for -p Give string on STDIN without newline (or add a -l option to the program) echo -n Hello | nest.pl  nest.pl: #!/usr/bin/perl -p$\=")"x s/.(?=.)/$&(/g  # PHP, 63 Bytes <?=str_pad(join("(",$s=str_split($argv)),count($s)*3-2,")‌​");


Previous version 64 Bytes

<?=join("(",$s=str_split($argv)).str_pad("",count($s)-1,")");  • You can save two bytes by using <?= instead of echo  and another one if you set$s to the result of the str_split call instead of $argv, and then use count($s) instead of strlen($s) Oct 18, 2016 at 20:00 • 63 bytes: <?=str_pad(join("(",$s=str_split($argv)),count($s)*3-2,")");- wordwrap would beat the split/join combination, but unfortunately fails if the input contains whitespace. Oct 19, 2016 at 13:15
• @Titus nice alternative Thank You Oct 19, 2016 at 14:08

## Perl, 25 bytes

Thanks to @Ton Hospel for golfing out 4 bytes.

24 bytes of code + -F.

$"="(";say"@F".")"x$#F


Needs -F and -E flags :

echo -n "I love lisp" | perl -F -E '$"="(";say"@F".")"x$#F'


Note that if you try this on an old version of perl, you might need to add -a flag.

Another interesting way (a little bit longer though : 28 bytes) :
Thanks to Ton Hospel once again for helping me getting this one right.

#!/usr/bin/perl -p
s/.(?=.)/s%\Q$'%($&)%/reg


(To use it, put the code inside a file and call it with echo -n "Hello" | perl nest.pl)

• You don't need the "" after the -F. You also don't need the -l if you demand the input string is entered without final newline: echo -n Hello | program Oct 19, 2016 at 4:59
• @TonHospel Right, I forgot (or didn't know, not sure) about that behavious of -F, thanks. (I was wondering how to get the input without the final newline, thanks for that too)
Oct 19, 2016 at 5:23
• perl -F -E '$"="(";say"@F".")"x$#F' Oct 19, 2016 at 7:27
• You can get your other idea working with something like s/.(?=.)/s%$'%($&)%/reg, but it of course doesn't support strings containing regex metacharacters Oct 19, 2016 at 10:31
• @TonHospel Thanks a lot for all of that! (About the second one, I added \Q to support regex metacharacters) :-)
Oct 19, 2016 at 15:11

# GNU sed, 3735 31 bytes (30 +1 for -r argument)

Pure linux sed solution

:;s/([^(])([^()].*)$/\1(\2)/;t  1. Naming the subsitution :; then calling it recursively with t 2. Making 2 regex groups: • First group is first char of two consecutive characters which are not parenthesis • Second group is the second consecutive character and the rest of the string until end of line 3. Add parenthesis around the second group \1 ( \2 ) Edit: Thanks to @manatwork for helping removing 4 characters! Online tester • Using only 2 groups seems to be enough. Capture the 2nd and 3rd together. Oct 19, 2016 at 23:06 • Oh, and sorry, but command line options necessary to change the interpreter's default behavior for your code to work, have to be included in the size count. The barely necessary -e to pass the code to the interpreter is for free. (Ok, sed is happy without it too.) So for sed -re '…' you count +1. Oct 20, 2016 at 8:04 • Blank labels are a GNU sed feature/bug, so maybe the title should be GNU sed. Oct 20, 2016 at 13:43 # 05AB1E, 222119 18 bytes ¤Ug<©FN¹è'(}X®')×J  Try it online! Explanation: ¤Ug<©FN¹è'(}X®')×J #implicit input, call it A ¤U #push the last letter of A, save it to X g<© #push the length of A, subtract 1, call it B and save it to register_c F } #repeat B times N¹è #push the Nth char of A '( #push '(' X #push X ®')× #push ')' repeated B times J #join together #implicit print  # Vim, 17 bytes $qqha(<Esc>A)<Esc>%h@qq@q

Goes from end to beginning, because otherwise you trip over the )s you've already written. Uses ha instead of i to fail when it reaches the beginning.

Usually, you wouldn't do two separate inserts like this; you'd do something like C()<Esc>P to save a stroke. But the positioning doesn't work as well this time.

• You can use the <End> key in insert mode instead of leaving insert mode and doing A Nov 30, 2016 at 1:09
• @BlackCap That's not a byte. I'd need to count strokes instead of bytes. (And Vimgolf is a better game when you ban cursor keys, though the difference here is trivial.) Nov 30, 2016 at 1:26

## Jellyfish, 19 18 bytes

P
,+>
_  {I
/'␁'(


The character ␁ is the unprintable control character with byte value 0x1. Try it online!

## Explanation

This is a pretty complex Jellyfish program, since many values are used in multiple places.

• I is raw input, read from STDIN as a string.
• '( is the character literal (.
• The { (left identity) takes '( and I as inputs, and returns '(. The return value is never actually used.
•  is thread. It modifies { to return the character ( for each character of I, resulting in a string of (s with the same length as I.
• > is tail; it takes the string of (s as input and chops off the first character.
• + takes as arguments the string of (s and the unprintable byte, and adds the byte value (1) to each character. This gives an equal-length string of )s. Using the character ␁ guarantees that the return value is a string, and not a list of integers.
• On the lower left corner, / takes the unprintable byte, and returns a function that takes two arguments, and joins the second argument with the first one once (since the byte value is 1).
• _ takes this function, grabs the arguments of the lower { (which were '( and I), and calls the funtion with them. This inserts the character ( between every pair of characters in I.
• , concatenates this string with the string of )s, and P prints the result.

# Convex, 10 bytes

_'(*\,(')*


Try it online!

# ><>, 37 bytes

i:0(?\'('
$,2l~/~ /?(2:<-1$')'
>~ror:


Row by row

1. Pushes each char from input with an opening parenthesis after each
2. Removes EOF and the last opening parenthesis and pushes the stack length
3. Uses a comparison with half the stack length to push the closing parenthesis
4. Prints the content of the stack

Try it online!

# Perl, 36 bytes (34 + 2 for -lpflag)

Thanks to Dada for pointing out a bug and saving one byte (in total)!

Splits the string into an array, then joins it with the (delimiter. We directly add the closing )since lengthreturns the length of the string before the join.

$_=(join"(",split//).")"x(y///c-1)  Try it here! • Sure you don't need -l flag? I doesn't seem to work when I try it... Or maybe I missed something? – Dada Oct 18, 2016 at 20:49 • Also, you can write y///c-1 instead of -1+length to save 2 bytes. – Dada Oct 18, 2016 at 20:51 • @Dada indeed, -l is needed when you run this with the terminal. I'm always doing these things on Ideone and it's not needed there... Editing! (and thanks for the tip!) Oct 18, 2016 at 20:54 • You could also do $_=(join"(",@a=split//).")"x(@a-1) which is a bit more verbose and the same number of bytes as the y///c-1. Or well, depends on the definition of verbose. Oct 18, 2016 at 21:25
• You can again drop the -l option by demanding that the input string is entered without final newline, echo -n Hello | program Oct 19, 2016 at 4:55

# Brain-Flak103 97 Bytes

Includes +3 for -c

{({}<><(((((()()){}()){}){}){})>)<>}<>({}<([][()]){({}[()()]<(({})()<>)<>>)}{}>){({}<>)<>}<>{}


Try it Online!

Explanation:

#reverse the stack and put a 40 between every number
{({}<><(((((()()){}()){}){}){})>)<>}<>
{                                  }   #repeat this until the stack is empty
({}                            )      #pop the top and push it after
<>                                 #switching stacks and
<(((((()()){}()){}){}){})>       #pushing a 40 (evaluated as 0)
<>    #switch back to the first stack
<> #switch to the stack that everything is on now

#put as many )s on the other stack as needed
({}                                      ) #pop the top letter and put it  back
#after doing the following
#This leaves ( on the top
<                                    >  #evalute this part as 0
([][()])                               #push the height of the stack minus one
{                        }    #repeat until the "height" is 0
({}[()()]              )     #pop the "height" and push is minus two
<            >      #evaluate to 0
(        )         #push:
({})              #the top of the stack (putting it back on)
()            #plus one onto
<>          #the other stack
<>       #switch back to the other stack

{}  #pop what was the height of the stack

#move the string of letters and (s back, reversing the order again
{        }     # repeat until all elements are moved
(    )        # push:
{}           # the top of the stack after
<>         # switching stacks
<>      # switch back to the other stack
<>   # switch to the stack with the final string
{} #pop the extra (

• Beat me to it. +1 Oct 18, 2016 at 20:35
• Hmm. I thought that reusing the 40 to avoid pushing a large integer again would save you a lot of bytes, but the best I can come up with is {({}<><(((((()()){}()){}){}){})>)<>}<>({}<(({})<>())><>)([]){({}[()()]<(<>({})<>)>)}{}{}{({}<>)<>}<>{} which is two bytes longer... Oct 18, 2016 at 20:44
• Thanks for giving me the idea to reuse the 40. I got it down to 95+3. Why is it 3 bytes for -a in Brain-Flak anyway? Oct 18, 2016 at 21:34
• Oh, nice work! The +3 bytes is standard for special command line flags. Which is unfortunate, but something I can put up with. I've actually been thinking of ways to shorten this, but I'm not exactly sure how yet. Oct 18, 2016 at 21:36
• Isn't it normally 2 bytes? one for the - and one for the flag? You could have a flag for normal execution like Perl does with -e. That way it would only be 1 extra byte. Oct 18, 2016 at 21:38