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

text:
# Question
Title: 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!

# Answer
# Python, ~~41~~ ~~39~~ 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.
> 69 votes

# Answer
## 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.
> 48 votes

# Answer
## JavaScript (ES6), ~~40~~ ~~34~~ 33 bytes

*Saved 6 bytes, thanks to ETHproductions*

A recursive function.

```
f=([c,...s])=>s+s?c+`(${f(s)})`:c

```

Try it online!
> 33 votes

# Answer
# 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
]

```
> 28 votes

# Answer
# 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

```
> 25 votes

# Answer
# 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.
> 19 votes

# Answer
## 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 `)`.
> 19 votes

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

```
> 18 votes

# Answer
## 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.
> 15 votes

# Answer
# 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

```
> 14 votes

# Answer
## \>\<\>, ~~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.
> 14 votes

# Answer
# 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
    )
;

```
> 13 votes

# Answer
# 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;}

```
> 11 votes

# Answer
# 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.
> 10 votes

# Answer
## PowerShell v2+, 46 bytes

```
param([char[]]$a)($a-join'(')+')'*($a.count-1)

```

Takes input string, `char`-array's it, `-join`s the array together with open parens `(`, then concatenates on the appropriate number of closed parens `)`.
> 9 votes

# Answer
# 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
                   }

```
> 9 votes

# Answer
# 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

```
> 9 votes

# Answer
## *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!
> 9 votes

# Answer
# PHP, 63 Bytes

```
<?=str_pad(join("(",$s=str_split($argv[1])),count($s)*3-2,")");

```

Previous version 64 Bytes

```
<?=join("(",$s=str_split($argv[1])).str_pad("",count($s)-1,")");

```
> 8 votes

# Answer
# 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

```
> 8 votes

# Answer
## 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`)
> 8 votes

# Answer
# 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

```
> 8 votes

# Answer
# GNU sed, ~~37~~ ~~35~~ 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
> 8 votes

# Answer
# 05AB1E, ~~22~~ ~~21~~ ~~19~~ 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

```
> 6 votes

# Answer
# 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.
> 6 votes

# Answer
## 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.
> 6 votes

# Answer
# Factor, 81 bytes

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

```
> 4 votes

# Answer
# Convex, 10 bytes

```
_'(*\,(')*

```

Try it online!
> 4 votes

# Answer
# Brain-Flak 103 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 (

```
> 4 votes

# Answer
# \>\<\>, 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!
> 4 votes

# Answer
# Perl, 36 bytes (34 + 2 for `-lp`flag)

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 `length`returns the length of the string before the `join`.

```
$_=(join"(",split//).")"x(y///c-1)

```

Try it here!
> 4 votes

# Answer
# Brachylog, ~~35~~ ~~28~~ 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

```
> 4 votes

# Answer
# 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(!)))))))))))
> 4 votes

# Answer
# 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
> 4 votes

# Answer
# 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!

```
> 4 votes

# Answer
# 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++;}

```
> 3 votes

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

```
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
# 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
> 3 votes

# Answer
# 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))))))))))"

```
> 3 votes

# Answer
## 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))))"

```
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
## Ruby, ~~41~~ 29 bytes

~~`->s{s.split("").join(?()+?)*(s.length-1)}`~~

```
->s{(s.chars*?()+?)*~-s.size}

```

Thanks @ValueInk
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# Pyth - 9 bytes

```
+j\(Qsm\)

```

Try it online here.
> 2 votes

# Answer
## Mathematica, ~~45~~ 43 bytes

```
#2<>"("<>#<>")"&~Fold~Reverse@Characters@#&

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# PHP, ~~51~~ ~~60~~ ~~68~~ 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;}

```
> 2 votes

# Answer
# CJam, ~~12~~ 11 bytes

*One byte saved by Martin Ender.*

```
q_'(*\,(')*

```

Try it online
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# Pyth, 10 characters

```
+j\(Q*\)tl

```

Try it online!

Joins the input on `(`, and appends `length - 1` closing parens afterwards.
> 2 votes

# Answer
**Scala, 58 bytes**

```
"Hello world!"match{case s =>s.mkString("(")+")"*s.length}

```

Could be shorter
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# , 9 bytes

```
$òys$)hhl

```

Try it online!
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
## 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+@)

```
> 2 votes

# Answer
# , 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.

### , 57 bytes

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

```

Try it online!
> 2 votes

# Answer
# Kotlin, ~~83~~ 63 bytes

*-20 bytes using `toList`; thanks to 12Me21 tipping me off this could be shorter.*

```
{s:String->s.toList().joinToString("(")+")".repeat(s.length-1)}

```

Try it online!
> 2 votes

# Answer
# Forth (gforth), 66 58 bytes

```
: f over 1 type 1 -1 d+ dup 0> if ." ("recurse ." )"then ;

```

Try it online!

-8 bytes by switching to a recursive solution

### Explanation

Prints the first character of the string. If it's not the last character in the string, print an open parentheses, recursively call on the remainder of the string, and print a close parentheses.

### Code Explanation

```
: f             \ start a new word definition
  over 1 type   \ print the first character of the string
  1 -1 d+       \ remove the first character of the string
  dup           \ duplicate the string length value
  0> if         \ check if remaining string length is greater than 0
    ." ("       \ print an open parentheses
    recurse     \ call recursively on remainder of string
    ." )"       \ print a close parentheses
  then          \ end the if block
;               \ end the word definition

```
> 2 votes

# Answer
# Vyxal, 7 bytes

```
L‹k(*sY

```

Try it Online!

Get gamed on @emanresuA

## Explained

```
L‹k(*sY
L‹      # Push the length of the input, but decremented
  k(    # Push "()"
    *   # and repeat it ↑↑ times
     s  # sort that
      Y # and interleave it with the input

```
> 2 votes

# Answer
# JavaScript (Node.js), 35 <sup>~~40~~</sup> bytes

Only 2 bytes above the best JS answer! (using array of characters as input, as OP apparently allowed in his comments)

```
s=>s.reduceRight((a,e)=>e+`(${a})`)

```

The `reduceRight` combines the advantage of the `reduce` (`n-1` iterations for `n` items, because in the output there is always one less couple of parenthesis than characters) with a `reverse` (necessary in this approach for accumulating the nesting by starting with the end)

Try it online!
> 2 votes

# Answer
## Perl 5, 27 bytes (25 + 1 for `-l` \+ 1 for `-n`)

This is a translation of Wheat Wizard's approach to Perl.

```
say$_.")"x s/.(?!$)/$&(/g

```

Run it like this:

```
perl -nlE 'say$_.")"x s/.(?!$)/$&(/g' <<< 'Hello'

```

Explanation:

```
say$_.")"x s/.(?!$)/$&(/g
           s/.(?!$)/   /g # replace every char not followed by end of string ...
                    $&    # ... with the full match (that's the one char)
                       (  # and an open parenthesis
           s/.(?!$)/$&(/g # this operates on and changes $_ and ...
                          # ... returns the number of substitutes
      ")"x                # repeat closing paren number of substitues times
     .                    # append
   $_                     # to the string that has already been changed to f(o(o
say                       # print with newline

```
> 1 votes

# Answer
## Pyke, 9 bytes

```
\(JQl\)*+

```

Try it here!
> 1 votes

# Answer
## Racket 195 bytes

```
(let p((r "")(l(reverse(string->list s)))(i 0))(cond[(= i(length l))r][(= i 0)(set! r(string(list-ref l i)))
(p r l(+ 1 i))][(set! r(string-append(string(list-ref l i))"("r")" ))(p r l(+ 1 i))]))

```

Ungolfed:

```
(define (f s)
  (let loop ((r "")
             (l (reverse (string->list s)))
             (i 0))
    (cond
      [(>= i (length l)) r]
      [(= i 0) (set! r (string (list-ref l i)))
               (loop r l (add1 i))]
      [else (set! r (string-append (string (list-ref l i)) "(" r ")" ))
            (loop r l (add1 i))]
      )))

```

Testing:

```
(f "Hello")

```

Output:

```
"H(e(l(l(o))))"

```

Edit: 2 bytes saved following suggestion by @JonathanFrech (add1 to + 1)
> 1 votes

# Answer
# Python 3, 40 chars

```
s=input()
print("(".join(s)+len(s)*")")

```
> 1 votes

# Answer
# Gema, ~~31~~ 13 characters

Shamelessly borrowing Titus's idea from his recursive PHP solution.

```
\B?=?
?#=(?#)

```

Sample run:

```
bash-4.3$ echo -n 'Hello world!' | gema '\B?=?;?#=(?#)'
H(e(l(l(o( (w(o(r(l(d(!)))))))))))

```
> 1 votes

# Answer
# Groovy, ~~38~~ 36 Bytes thanks to @manatwork

```
{it.reverse().inject{r,i->i+"($r)"}}

```

Yeah, the C&P messed up the first time.
> 1 votes

# Answer
# Scala, 46 bytes

```
(s:String)=>(s.init:\(""+s.last))(_+"("+_+")")

```

Explanation:

```
(s:String)=>    //define a function
  (s.init       //take everything but the last char
   :\           //foldRight
   (""+s.last)    //with the last char as a string as a start
  )(              //combine the chars right to left with this function:
    _+"("+_+")"   //take the char, append "(", append everything we've got so far, append ")"
  )

```
> 1 votes

# Answer
# Java, 72 bytes

```
(a,s,l)->{l=a.length;s=""+a[--l];for(;l>0;)s=a[--l]+"("+s+")";return s;}

```

## Ungolfed

```
public class Main {

  interface X {
    String f(char[]a,String s,int l);
  }

  static X x = (a,s,l) -> {
    l = a.length;
    s = "" + a[--l]; // start with the last character
    for (;l>0;)
      s = a[--l] + "(" + s +")"; // wrap in parentheses and prepend with the previous letter.
    return s;
  };

  public static void main(String[] args) {
    System.out.println(x.f("Hello World!".toCharArray(),"",0));
  }
}

```
> 1 votes

# Answer
# Python 2, ~~60~~ ~~57~~ 51 Bytes

```
def c(s):if(len(s)==1):return s;return s[0]+"("+c(s[1:])+")"

```

After some clarification on the rules from @manatwork on white space,

```
def c(s):return s if(len(s)==1)else s[0]+"("+c(s[1:])+")"

```

Thanks again @manatwork

```
def c(s):return s[0]+"("+c(s[1:])+")"if s[1:]else s

```

Ungolfed:

```
def c(s):
    if(len(s)==1):
        return s;
    return s[0]+"("+c(s[1:])+")"

```

Recursively calls itself and adds to the string.

```
c("CodeGolf") = 'C(o(d(e(G(o(l(f)))))))'

```
> 1 votes

# Answer
# C, ~~84~~ ~~82~~ ~~76~~ ~~70~~ ~~68~~ 66 Bytes

```
i;f(char*s){for(i=1;*s+~i;putchar(*s?i&1?*s++:40:41),i+=*s?1:-2);}

```

Now using just one for loop and one putchar...

Test is like this

```
main(c,v)char**v;
{
    f(v[1]);puts("");
    f("foobar");puts("");
    f("code-golf");puts("");
}

```

output

```
H(e(l(l(o( (W(o(r(l(d))))))))))
f(o(o(b(a(r)))))
c(o(d(e(-(g(o(l(f))))))))

```
> 1 votes

# Answer
## Python 50 49 bytes

saved 1 byte (actually 3) thanks to @ETHproductions

This is my recursive version written in Python. Would probably be shorter the iterative aproach.. but I simply like recursion `:)`

```
F=lambda s:s[0]+'('+F(s[1:])+')'if len(s)>1else s

```
> 1 votes

# Answer
# Dart 44 bytes

```
p(s)=>s.split("").join("(")+")"*~-s.length;

```

I tried to be clever, but nothing beat this simple version. Notable mention:

```
r(s,[x=0])=>s[x++]+(x<s.length?"(${r(s,x)})":"");
q(s)=>s[0]+((s=s.substring(1))==""?s:"(${q(s)})");

```

but they drowned in necessary parentheses.
> 1 votes

# Answer
# Python 3, 43 bytes

```
lambda x:print(*x,sep='(',end=')'*~-len(x))

```

Longer than shortest Python submission, but it is fairly different, so I thought I should post it. It is a function, but prints to STDOUT.
> 1 votes

# Answer
## Clojure, ~~94~~ ~~60~~ ~~59~~ 48 bytes

-34 by making it a actual recursive solution. The biggest saving here was getting rid of the `repeat` part to generate the end brackets.

-1 by rearranging it, eliminating a conditional.

-11 bytes thanks to NikoNyrh. Now deconstructs the parameter directly.

```
(defn n[[f & r]](if(str f(if r(str\((n r)\))))))

```

Recursive. Basically `(str head "(" (recur tail) ")")`, with the brackets being added only if a tail exists.

Uses unoptimized recursion. Can handle strings up to around 5235 characters long.

Ungolfed:

```
(defn nest [[f & r]]
    (if f ; When it exists, construct string and recur, else, base-case
      (str f (if r (str \( (nest r) \))))))

```
> 1 votes

# Answer
# Haskell, ~~38~~ 30 bytes

*8 bytes saved thanks to @JanDvorak*

```
f[x]=[x]
f(x:s)=x:'(':f s++")"

```

This is my first attempt at a haskell golf, probably not optimal yet.

# Explanation

We define a function `f`. If this function receives input that matches the pattern `[x]`, that is a length 1 string, we return the input. If we receive anything else as input we return the `x:'(':f s++")"`, or the first character plus the rest result of `f` on the rest of the string all enclosed in parentheses.
> 1 votes

# Answer
# Groovy, 46 bytes

```
{it.reverse().inject{r,i->")$r($i"}.reverse()}

```
> 1 votes

# Answer
# Swift 3.1,  ~~85~~  83 bytes

This is an anonymous function accepting an Array of Strings and returning a String.

```
{$0.joined(separator:"(")+String(repeating:")",count:$0.count-1)}as([String])->String

```

**Try it here!**

# Swift 3.1,  ~~88 87~~  86 bytes

This is a named function accepting an Array of Strings and printing a String.

```
func f(n:[String]){print(n.joined(separator:"(")+(1..<n.count).map{_ in")"}.joined())}

```

**Try it here!**
> 1 votes

# Answer
# Ly, 50 bytes

```
iyspr1[1[=!["("o1$]p1$]1[=[pp2$]p1$]o]l1-[")"o1-];

```

Try it online!

This is ridiculous. Ly is lacking severely in the string manipulation department.
> 1 votes

# Answer
# Java 8 (~~63~~ 82 bytes)

"s" is a char\[\]

~~s-\>{String r="",p=r;for(char c:s){r+="("+c;p+=")";}return r+p;}~~

```
s->{String r="",p=r;for(char c:s){if(r==p)r+=c;else{r+="("+c;p+=")";}}return r+p;}

```

Edit: I didn't realise there aren't parentheses around the whole string.
> 1 votes

# Answer
# Implicit, ~~24~~ 23 bytes

```
~@~.(0-1@40@~.);;(0@41;

```

Try it online!

Ungolfed/explained:

```
~@~.     # read first character, print, read second, increment
(0       # do-while top of stack truthy
 -1      #  decrement top of stack
 @40     #  print open parenthesis (ASCII 40)
 @       #  print top of stack
 ~.      #  read char and increment
)        # while top of stack truthy
;;       # pop top two values (EOF, last char)

(0       # do-while top of stack truthy
 @41     #  print close parenthesis (ASCII 41)
 ;       #  pop top of stack
¶        # (implicit) forever

```

Test cases:

```
Nest a string
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

foobar
f(o(o(b(a(r)))))

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

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

a
a

42
4(2)

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 111 bytes

```
	INPUT LEN(1) . O REM . N
	W =SIZE(N)
N	N LEN(1) . X REM . N	:F(O)
	O =O '(' X	:(N)
O	OUTPUT =O DUPL(')',W)
END

```

Try it online!
> 1 votes

# Answer
# Python 3.6+, 39 bytes

```
z=lambda x,*y:x+f'({z(*y)})'if y else x

```

Takes each character as an individual argument (can be used like `z(*'asdf')`). This uses recursion with iterable unpacking and f-string interpolation.

---

Note: This is *almost* non-competing. Python 3.6 was released after this challenge was posted, but was feature-frozen in beta on 2016-09-12, so this feature was available before the challenge was posted.

---

Though it turns out you can do it in the same number of bytes with %-interpolation (this works on more Python versions):

```
z=lambda x,*y:x+'(%s)'%z(*y)if y else x

```
> 1 votes

# Answer
## Canvas, 8 bytes

```
(＊；Ｌ╷)×＋

```

Try it here!
> 1 votes

# Answer
# Whitespace, 132 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_characters_as_STDIN][T  T   T   _Retrieve][S S S T  S T S S T   N
_Push_41_)][T   S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_PRINT_TRAILING][S N
S _Duplicate][N
T   S T N
_If_0_Jump_to_Label_SKIP][S S S T   S T S S S N
_Push_40_(][T   N
S S _Print_as_character][N
S S T   N
_Create_Label_SKIP][S N
S _Duplicate][T T   T   _Retrieve][T    N
S S _Print_as_character][S S S T    N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_TRAILING][S S S T   N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   S S S N
_If_0_Jump_to_Label_EXIT][S S S T   S T S S T   N
_Push_41_)][T   N
S S _Print_as_character][N
S N
S N
_Jump_to_Label_PRINT_TRAILING]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Since Whitespace's STDIN don't know when the input is done since it can only read a single character or number at a time, the input will need a trailing `)` to indicate we're done inputting (which is possible since the challenge rules state: "*For simplicity's sake, you may also assume the input will not contain parentheses*").

**Explanation in pseudo-code:**

```
Integer n = 0
Start LOOP:
  Character c = read character from STDIN
  If(c == ')'):
    Jump to function PRINT_TRAILING
  If(n != 0)
    Print '(' to STDOUT
  Print c to STDOUT
  n = n + 1
  Jump to next iteration of LOOP

function PRINT_TRAILING:
  n = n - 1
  If(n == 0)
    Stop program
  Print ')' to STDOUT
  Jump to function PRINT_TRAILING

```
> 1 votes

# Answer
# , 29 bytes

```
f=:(')'#~<:@#),~}.@,@('(',.])

```

Try it online!
> 1 votes

# Answer
## C++, 66 bytes

```
[&](string s){return s[1]?s.substr(0,1)+"("+f(s.substr(1))+")":s;}

```

Try it Online

## Matlab, 45 bytes

```
@(s)fold(@(x,y)strcat(y,'(',x,')'),fliplr(s))

```

Try it Online!

The problem with this is that octave in try it online doesn't really support the `fold` function which of course exists in Matlab. Let me know if I should delete this solution since we can't test it on tio.
> 1 votes

# Answer
# Keg, ~~22~~ ~~16~~ ~~15~~ 12 bytes

```
?^⑷`(`⑸÷_(\)

```

## Explained

```
?^⑷`(`⑸÷_(\)
#?^         Takes input and reverse it
#⑷`(`⑸÷    Maps an additional "(" to each letter
#÷_         Takes the last item and removes the extra bracket
#(\)        Appends a ")" for each item on the stack

```

## Answer History

### 15 bytes

```
?!&("\()_^`)`&*

```

Try it online!

-1 byte due to some sort of stack-mechanic magic. I don't really know what I did, but it's shorter! Also, it's *still* ASCII only!

Explained:

```
?!&("\()_^`)`&*
?!&             #Take input and store the length in the register
   ("\()        #For each item on the stack, right shift and push a "("
        _^      #Pop the top and reverse
          `)`&* #Push ")" multiplied by the register (python-like string multiplication)

```

## Answer History

### 16 bytes

```
?!&("\()'^_`)`&*

```

Try it online!

-6 bytes due to usage of the register rather than a custom variable. Also, that's 16 *UTF-8/ASCII* bytes for once.

Explained:

```
?!&("\()'^_`)`&*
?!&                 #Take input and store the length in the register
   ("\()            #For each item on the stack, right shift and push a "("
        '^_         #Left shift the stack, reverse and pop the top of stack
           `)`&*    #Push ")" multiplied by the register (python-like string multiplication)

```

### 22 bytes (SBCS)

```
?!®c("\()'^_(©c|\))^(,

```

Try it online!

Note that due to a newly discovered bug, TIO won't work properly, but the github interpreter *will* work correctly.

## Explanation

```
#?!®c("\()'^_(©c|\))^(,
?!®c    #Get user input, and store the length in variable c
("\()   #For each item in the stack, right shift and push a "("
'^_ #Reverse the stack and pop the last most "("
(©c|\)) #For _ in range(0, var_c): append a ")"
^(, #Reverse and print the stack as characters

```
> 1 votes

# Answer
# C (gcc), ~~97~~ 84 bytes

Thanks to ceilingcat for -13 bytes

```
f(char*b){printf(*++b?"%c(":"%c",*b);*b&&f(b)+printf(")");}a[99];main(){f(gets(a));}

```

Try it online!
> 1 votes

# Answer
# Gol\>\<\>, 21 bytes

```
TiE!tlF`(}}|~l2,R`)rH

```

Try it online!

**24 bytes**

```
TiE!trlF}8ss}|r~l2,R`)rH

```

It's hideous, I know. I am going to golf this profusely.

Try it online!
> 1 votes

# Answer
# Wren, 54 bytes

```
Fn.new{|x|x.map{|i|i+"("}.join()[0..-2]+")"*~-x.count}

```

Try it online!

# Wren, 36 bytes

I didn't write this myself. Therefore it is boring.

```
Fn.new{|x|x.join("(")+")"*~-x.count}

```

Try it online!
> 1 votes

# Answer
# Befunge-93, 33 bytes

```
~# <\,"()"_v#+1:~,
         :,_@#

```

Try it online!

Due to the `<` character, the first line should be read backwards.

`,` : Output the most recently read character.

`~` : Read a new character.

`1+#v_`: If there is no new character, go to the second line.

`")("`: Push parentheses characters onto the stack.

`,` : Output left parenthesis.

`\` : Bury the right parenthesis deeper in the stack so it won't output until the end.

The rest of the first line is code to special-case the first character so that it gets output without creating parentheses.

The second line then simply outputs the stack until it's empty.
> 1 votes

# Answer
# Burlesque, 16 bytes

```
'([]sa2./')j.*.+

```

Try it online!

```
'([]  # Insert "(" between each char
sa2./ # Find length/2
')j.* # That many ")"s
.+    # Concatenate

```
> 1 votes

# Answer
# GolfScript, 12 bytes

```
.'('*')'@,(*

```

What a cute little solution!

```
.            #Duplicate entry string
 '('*        #Join the string with left-paren
     ')'     #Right paren string
        @    #Bring up our duplicate
         ,   #Count the number of characters
          (  #Decrease that number by 1
           * #Add that many ')' to the end

```

Try it online!
> 1 votes

# Answer
## Unix TMG, 51 byte

```
p:parse(s)s:smark any(!<<>>)scopy s/d={2<(>1<)>}d:;

```

Works by recursive descent parsing.

Exploits absence of semicolons between parsing rules to make it two bytes shorter.
> 1 votes

# Answer
# Zig, 84 bytes

```
fn p(q:var)[]const u8{return[_]u8{q[0]}++if(q.len>1)"("++p(q[1..q.len])++")"else"";}

```

Try it

tests:

```
fn p(q: var) []const u8 {
    return [_]u8{q[0]} ++ if (q.len > 1) "(" ++ p(q[1..q.len]) ++ ")" else "";
}

const std = @import("std");
const Test = struct { in: []const u8, out: []const u8 };
test "it works" {
    comptime const tests = [_]Test{
        .{ .in = "Hello", .out = "H(e(l(l(o))))" },
        .{ .in = "foobar", .out = "f(o(o(b(a(r)))))" },
        .{ .in = "a", .out = "a" },
    };
    inline for (tests) |i| {
        std.testing.expect(std.mem.eql(u8, comptime p(i.in), i.out));
    }
}

```
> 1 votes

# Answer
# MAWP, 33 bytes

```
%|_!1A[1A~;85W;~]~;1A[1A~85W1M;~]

```

Try it!
> 1 votes

# Answer
# TI-Basic, ~~62~~ 64 bytes

```
For(I,1,2length(Ans)-2,2
sub(Ans,1,I)+"("+sub(Ans,I+1,length(Ans)-I
End
For(I,1,.5length(Ans
Ans+")
End
Ans

```

Takes input in `Ans`. Output is displayed and stored in `Ans`.
> 1 votes

# Answer
# Python 3, 51

Just a simple recursive function.

```
lambda s:s if len(s)<2else s[0]+"("+nest(s[1:])+")"

```

Try it online!
> 1 votes

# Answer
# Underload, 18 bytes

```
(~*a~a:*~a*^~):()~

```

Try it online!

Takes input as a reversed list of characters.

### Explanation

Arbitrary-length list handling is a little weird in Underload.
Typically, inputs are passed in the form `(a)~(b)~(c)~^S` with the assumption that there is a function on the stack. This pushes each input one at a time and then swaps them with the function, keeping the function on top, then finally executes the function and prints the top of the stack.

For arbitrary-length lists however, we need to make 2 changes.
Firstly, the function must be self-replicating, and must operate on each individual item on the stack.
Secondly, inputs must be passed in the form `(a)~^(b)~^(c)~^!S`
This executes the function after each input, with the expectation that after the function is run, the top of the stack will be the function. (`^` pops the function from the stack before execution).

```
(~*a~a:*~a*^~):()~
(            )       Main function
 ~                     Swap the top two items on the stack
  *                    Concatenate them
   a                   Wrap the result in parentheses
    ~a:*~a*^~          Function self-replication.
                         Assumed that the top of the stack is the result of the function
                         and the 2nd item is the function.
                         ie for stack [f, a], produces [f, a, f]
              :()~   Duplicate function and push an empty string between them
                       Resulting stack when execution begins is
                       ['~*a~a:*~a*^~', '', '~*a~a:*~a*^~']

```
> 1 votes

# Answer
# ayr, 20 bytes

```
(:1},;'(',"),')'#}&#

```

# Explained

```
           }&#  Length - 1
       ')'#     Repeat ')' that many times
      ,         Append to end of
(: xx)          The result of applying input to partial application xx
             Where xx is:
    '(',"  Append '(' to beginning of each char
  ,;       Convert from vec of strs to str (mix before flatten)
1}         Remove first char

```
> 1 votes

# Answer
# KamilaLisp v0.2, 32 (APL SBCS)

```
$(⌿.← \λ(x y)\⍫∊ "{?y}({?x})")∘⌽

```

Equivalent to `$(foldl1 \lambda(x y)\str:format "{?y}({?x})")@reverse`.
> 1 votes

# Answer
# Thunno `D`, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 bytes

```
'(sjsL')*+ZH

```

Attempt This Online!

#### Explanation

```
'(sjsL')*+ZH  # Implicit input
  sj          # Join the input by...
'(            # The "(" character
    sL        # Push the length of the input
        *     # And multiply it by...
      ')      # The ")" character
         +    # Add these together
          ZH  # And remove the last character
              # Implicit output

```
> 1 votes

# Answer
# Pip, ~~15~~ 12 bytes

```
OaJ'(')X#a-1

```

Attempt This Online!

*-3 thanks to @DLosc*

#### Explanation

```
OaJ'(')X#a-1  ; Input on command line
 a            ; The input string
  J           ; Joined by
   '(         ; The character "("
O             ; Output and pass through
     ')       ; The character ")"
       X      ; Repeated this many times
        #a    ; Length of input
          -1  ; Minus one
              ; Implicit output

```

Old:

```
(aJ'().')X(D#a)  ; Input on command line
 a               ; The input string
  J              ; Joined by
   '(            ; The character "("
(    ).          ; Concatenated with
       ')        ; The character ")"
         X(   )  ; Repeated this many times
            #a   ; Length of the input
           D     ; Minus one
                 ; Implicit output

```
> 1 votes

# Answer
# Nibbles, 8 bytes (16 nibbles)

```
`)+.$:"("$^,@")"

```

```
                    # first string:
   .                # map over
    $               # input:
     :              #   join
      "("           #   "("
         $          #   to each element
  +                 # flatten this list
`)                  # and remove the first element;
                    # second string:
          ^         # replicate
             ")"    #   ")"
           ,@       #   length of input times
                    # (and the two strings are printed
                    # one-after-the other in the output)

```
> 1 votes

# Answer
# TypeScript's Type System, 212 73 bytes

```
type X<S>=S extends`${infer A}${infer B}`?B extends""?A:`${A}(${X<B>})`:S

```
* Remove three redundant types (Jacob)
> 1 votes

# Answer
# tcl, 66

```
puts [join [split $s ""] (][string repe ) [expr [string le $s]-1]]

```

Testable on http://rextester.com/live/SAXFO71660
> 0 votes

# Answer
# ForceLang, 132 bytes

```
def S set
S a io.readln()
S i 0
S b ")"
label 1
io.write a.charAt i
S i i+1
if i+-a.len
 io.write "("
 goto 1
io.write b.repeat i+-1

```
> 0 votes

# Answer
# Japt, 11 bytes

```
ç q') iUq'(

```

Try it online!

Takes an array of 1-length strings as input.

### How it works

```
Uç q') iUq'(

Uç    Replace input array's every element with `undefined`
q')   Join with ")"
i     Insert to the beginning of above result...
Uq'(    Input array joined with "("

```

Uses a JS trick: `undefined` elements of an `Array` is converted to empty strings on `join`.
> 0 votes

# Answer
# Java 10, 71 bytes

```
s->{var r="";for(int i=s.length;i-->1;r="("+s[i]+r+")");return s[0]+r;}

```

Shorter than the existing two recursive Java answers.

Input as String-array of each character.

Try it online.

```
s->{               // Method with String-array parameter and String return-type
  var r="";        //  Result-String, starting empty
  for(int i=s.length;i-->1;
                   //  Loop backwards over the array, skipping the first character
    r=             //   Set the result to:
      "("          //    An opening parenthesis,
      +s[i]        //    appended with the current character,
      +r           //    appended with the current result-String,
      +")");       //    appended with a closing parenthesis
  return s[0]+r;}  //  Return the first character, appended with the result-String

```
> 0 votes

# Answer
# Gol\>\<\>, 37 bytes

```
14a*iov
!vo$P$>:oi:P?
:>~~:?!;9sso1-:

```

Try it online!

Reads from stdin, outputs to stdout

Explanation:

```
14a*            Pushes 1 (num of characters so far) and 40 (ASCII for open paren) onto stack
    io          Reads a character and outputs it
      v         Drops to next line of golfed code

      >         Directs pointer to the right
       :o       Duplicates and outputs the (
         i      Inputs a character
!v        :P?   Drops to next line of golfed code if no more chars
  o             Outputs character
   $P$          Increments the character counter

 >              Directs pointer to the right
  ~~            Discard unneeded stack values
    :?!;        Exits if counter == 0
        9sso    Outputs closing paren
            1-  Decrement counter
:             : Duplicate counter twice (so that it isn't discarded by the '~'

```
> 0 votes

# Answer
# Japt, 11 bytes

```
¬q'( +UÅî')

```

Try it
> 0 votes

# Answer
# Icon, 59 bytes

```
procedure f(s)
return(*s>1&s[1]||"("||f(s[2:0])||")")|s
end

```

Try it online!
> 0 votes

# Answer
# Red, 59 bytes

```
func[s][either 1 < length? s[rejoin[s/1"("f next s")"]][s]]

```

Try it online!
> 0 votes

# Answer
# Arturo, 44 bytes

```
f:$[s]->(one? s)?->s->~«|s\0|(|f drop s 1|)

```

Try it

```
f:$[s]->                   ; a function named f taking an argument s
(one? s)?                  ; does s have a length of one?
->s                        ; then return s
->                         ; otherwise return
    ~«                     ; interpolated string that spans the rest of the line
    |s\0|                  ; first character in s
    (                      ; followed by open paren
    |f drop s 1|           ; followed by calling f on s without its first char
    )                      ; followed by closing paren

```
> 0 votes

# Answer
# Thunno 2, 10 bytes

```
'(j$l⁻')×+

```

Attempt This Online!

#### Explanation

```
'(j$l⁻')×+  # Implicit input
'(j         # Join the input by "("
   $l⁻      # Length of input minus one
      ')×   # Multiplied by ")"
         +  # Concatenate the strings
            # Implicit output

```
> 0 votes

---
Tags: code-golf, string, balanced-string
---