g | x | w | all
Bytes Lang Time Link
063Nim250816T102614ZjanAkali
028APLNARS250815T100131ZRosario
012Pip250814T190107ZDLosc
044tinylisp 2250814T172039ZDLosc
007Jelly161018T184320ZJonathan
019Brachylog250814T054944ZDLosc
013Dyalog APL250814T043115ZAaron
252Bespoke250814T033609ZJosiah W
038AWK250312T194958Zxrs
010Uiua 0.15.0dev.2250306T203725ZRomanPro
035Python 3250306T181524ZThe Empt
040Brainfuck161018T194533ZAlex How
066Tcl170111T203848Zsergiol
010Thunno 2230603T183346ZThe Thon
073TypeScript's Type System230502T121100ZTristan
012Pip230311T140022ZThe Thon
044Arturo230501T205643Zchunes
035JavaScript Node.js230310T103634ZFhuvi
816Nibbles230311T150651ZDominic
064TIBasic211027T220511ZYouserna
nan230311T135254ZThe Thon
032KamilaLisp v0.2230310T200131ZKamila S
007Vyxal211026T193618Zemanresu
020ayr211103T142105ZZippyMag
007Vyxal211102T122656Zlyxal
018Underload211029T150420ZMayube
051Python 3211028T011716ZAlan Bag
033MAWP200809T150014ZRazetime
084Zig200302T222140Zpfg
051Unix TMG200228T154416ZAndriy M
012GolfScript200226T205912ZMathgeek
016Burlesque200225T093746ZDeathInc
01005AB1E191224T225832Zmabel
033Befunge93191224T192926Zhistocra
054Wren191224T090224Zuser8505
012Keg191015T215331Zlyxal
244Poetic191018T223516ZJosiahRy
084C gcc191017T031856Zgirobuz
021Gol><>191017T235057ZKrystosT
058Forth gforth180828T132626Zreffu
059Icon191015T070438ZGalen Iv
059Red191015T072930ZGalen Iv
195Racket161019T021502Zrnso
033JavaScript ES6161018T184517ZArnauld
066C++180828T092344ZDimChtz
029J180828T091439Zuser5812
011Japt180828T090617ZShaggy
132Whitespace180828T090540ZKevin Cr
037Gol><>180828T074613Zxornob
063Kotlin180525T180945Zsnail_
006Stax180524T154919ZKhuldrae
039Python 3.6+180524T225552ZBeefster
008Canvas180525T015745Zhakr14
111SNOBOL4 CSNOBOL4180524T184050ZGiuseppe
056R180524T181952ZJayCe
071Java 10180524T084025ZKevin Cr
011Japt180524T082747ZBubbler
023Implicit171110T181521ZMD XF
064QBIC161128T180855Zsteenber
082Java 8170901T133347ZRoberto
050Ly170901T090506ZLyricLy
083Swift 3.1170901T082331ZMr. Xcod
046Groovy170628T181353ZMagic Oc
030Haskell170611T174536ZWheat Wi
063PHP161019T123354ZTitus
132ForceLang170308T011205ZSuperJed
nanBrainFlak161019T014637ZWheat Wi
027Mathematica170108T224251Zuser6198
043Python 3170108T171657Znedla200
048Clojure170108T220430ZCarcigen
034Python161018T183941ZWheat Wi
014Dyalog APL161128T191918Zngn
036JavaScript161110T201513ZGrax32
009V161110T180810ZDJMcMayh
066C161020T183418Zcleblanc
030MSDOS .com file161018T203138ZMartin R
072Java161019T141406ZOlivier
018Jellyfish161019T101120ZZgarb
044Dart161024T081759Zlrn
010Actually161024T063710Zuser4594
058Scala161023T184416ZTrevor S
049Python161021T123711ZStefan
011CJam161019T171531ZNeorej
081Java161019T144233ZAxelH
081Factor161018T193820Zcat
nanGNU sed161019T222029ZDoomsday
010Pyth161020T020734ZSteven H
051Python 2161019T184820Zbiowease
074Bash / sed161019T203329ZDoomsday
036Groovy161019T130749ZMagic Oc
016k161019T173757Zskeevey
025Perl161018T204219ZDada
8179Java 7161018T192129ZNumberkn
063PHP161018T191717ZJör
025Brachylog161019T123718ZEmigna
046Scala161019T134747Zcorvus_1
043Mathematica161018T221657Zfreddiek
013Gema161019T084558Zmanatwor
082SWIProlog161019T120013ZEmigna
129Acc!!161019T070829ZDLosc
036Zsh161019T052730ZLinusKro
023Perl161019T044533ZTon Hosp
040Python 3161019T021522Zvpzomtrr
027Turtlèd161019T020423ZDestruct
029Ruby161018T184409Zanna328p
032C#161019T012414Zmilk
016MATL161018T193945ZLuis Men
097BrainFlak 97 Bytes161018T195917ZRiley
089C161018T195549Zcat
009Pyke161018T213543ZBlue
nanPerl 5161018T212030Zsimbabqu
061R161018T204213Zjmartind
018><>161018T204957ZMartin E
nanPerl 5161018T203017Zsimbabqu
nanPerl161018T203726ZSake
009Pyth161018T204951ZMaltysen
037><>161018T203608ZEmigna
027Ruby161018T203804Zm-chrzan
017Vim161018T195223Zudioica
010Convex161018T195012ZGamrCorp
01805AB1E161018T184944ZLuke
013J161018T192141Zmiles
030Haskell161018T191631Znimi
017Retina161018T184015ZMartin E
019APL161018T191054Zmarinus
01105AB1E161018T190858Zacrolith
044Brainfuck161018T190240Zuser5946
088Lua161018T185652ZIDid
046PowerShell v2+161018T184255ZAdmBorkB

Nim, 63 bytes

proc n(s=""):string=
 if s.len<2:s else:s[0]&'('&s[1..^1].n&')'

Attempt This Online!

APL(NARS), 28 chars

{1≥≢⍵:⍵⋄(↑⍵),'(',(∇1↓⍵),')'}

test:

  f←{1≥≢⍵:⍵⋄(↑⍵),'(',(∇1↓⍵),')'}
  f 'Hello'
H(e(l(l(o))))
  f 'Hello world!'
H(e(l(l(o( (w(o(r(l(d(!)))))))))))

Pip, 12 bytes

POa.:a&pJREa

Attempt This Online!

Explanation

Different approach from The Thonnu's 12-byte solution, which you should also upvote.

POa.:a&pJREa
POa           Pop the first character from the argument
   .:         Concatenate it to the following:
     a&       If the remainder of the argument is falsey (""), return it; else,
         REa  Recurse on the remainder of the argument
       pJ     Join p (builtin for "()") on the result

tinylisp 2, 44 bytes

(d F(\(s)(c(h s)(?(t s)(,(,"("(F(t s)))")")"

Try It Online!

Explanation

(d F(\(s)(c(h s)(?(t s)(,(,"("(F(t s)))")")""))))
(d F                                            ) ; Define F as
    (\(s)                                      )  ; A function of s:
         (c(h s)                              )   ; Cons head of s to...
                (?(t s)                      )    ; Is tail of s nonempty?
                         (,"("        )           ;  Concat open paren to
                              (F     )            ;  Recursive call
                                (t s)             ;  On tail of s
                       (,              ")")       ;  Concat that to close paren
                                           ""     ; Otherwise, empty string

Jelly, 9 8 7 bytes

Uses a modified form of Lyxal's 8 byte suggestion from 2021.

L’Ø(xż@

A full program that accepts a string and prints to stdout.

How?

L’Ø(xż@ - Link: list of characters, S  e.g. ['a','b','c'] (from input "abc")
L       - length {S}                        3
 ’      - decrement                         2
  Ø(    - literal ['(',')']                 ['(',')']
    x   - {['(',')']} times {len(S)-1}      ['(','(',')',')']
     ż@ - {S} zip with {that}               [['a','('],['b','('],['c',')'],[')']]
        - implicit, smashing print          a(b(c))

Original

At the time of posting, features newer than the question were not allowed to be used.

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

Brachylog, 19 bytes

l₁|⟨hc{b↰₀;")("c↻}⟩

Try it online!

Explanation

Recursion in Brachylog can be a bit fiddly, but I'm fairly happy with how this turned out.

l₁|⟨hc{b↰₀;")("c↻}⟩
l₁                   Base case: if the input's length is 1, return it unchanged
  |                  If that case fails, recursive case:
   ⟨ c            ⟩     Concatenate
    h                  The head (first character)
      {          }     with the result of this nested predicate:
       b                 Behead (remove first character)
        ↰₀               Call the 0th predicate (the whole line) recursively
          ;")("c         Concatenate the result with ")("
                ↻        Rotate the last character to the beginning

Dyalog APL, 13 chars

⊃{∊⍺⍵,¨'()'}/
 {         }/  Reduce over input
     ,¨        Concat each
   ⍺⍵            the strand of left and right args
       '()'      with the parens
  ∊            Flatten
⊃              And disclose the result

Bespoke, 252 bytes

given my string to nest:a(b)I blindly printed first of it
then repeated bracket nesting,as all my text characters raised my number of brackets
bracket,then a further character
if I do last,bracket after end is used,a number of repeated instants as seen

I rarely ever use the CONTROL OTHERWISE command in golfed Bespoke programs, but in this case, it let me omit three CONTROL ENDs that occur at the end of the program.

AWK, 38 bytes

{for(s=$NF;NF>1;)s=$(--NF)"("s")"}$0=s

Attempt This Online!

{for(s=$NF;  # catches if only one char
NF>1;)       # going backwards
s=           # set string
$(--NF)"("   # to previous char, parens
s")"}        # string, and another parens behind
$0=s         # set default output to string s

Uiua 0.15.0-dev.2, 10 bytes

⍜⇌/$")_(_"

Try it out!

Python 3, 35 bytes

lambda s:'('.join(s)+')'*(len(s)-1)

Classic string.join makes this too easy.

Try it online!

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
]

Tcl, 66 bytes

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

Try it online!

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

TypeScript's Type System, 212 73 bytes

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

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

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

JavaScript (Node.js), 35 40 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!

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)

enter image description here

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.

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

KamilaLisp v0.2, 32 (APL SBCS)

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

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

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

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

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

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*^~']

Python 3, 51

Just a simple recursive function.

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

Try it online!

MAWP, 33 bytes

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

Try it!

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

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.

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!

Burlesque, 16 bytes

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

Try it online!

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

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

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.

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!

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

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.

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!

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!

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            

Icon, 59 bytes

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

Try it online!

Red, 59 bytes

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

Try it online!

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)

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!

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.

J, 29 bytes

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

Try it online!

Japt, 11 bytes

¬q'( +UÅî')

Try it

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

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 '~'

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!

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!

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

Canvas, 8 bytes

(*;L╷)×+

Try it here!

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!

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!

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

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.

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)

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

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.

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.

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!

Groovy, 46 bytes

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

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.

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

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

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

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

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.

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

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.

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

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.

V, 9 bytes

$òys$)hhl

Try it online!

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

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.

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

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.

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.

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

Scala, 58 bytes

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

Could be shorter

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

CJam, 12 11 bytes

One byte saved by Martin Ender.

q_'(*\,(')*

Try it online

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

Factor, 81 bytes

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

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

Pyth, 10 characters

+j\(Q*\)tl

Try it online!

Joins the input on (, and appends length - 1 closing parens afterwards.

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

Bash / sed, 74 bytes

y=$(echo $1|sed "s/./\0(/g");z=$(echo $1|sed "s/./)/g");echo ${y%?}${z%?}

To test, put this code into a file, and run the shell script with any arguments.

Groovy, 38 36 Bytes thanks to @manatwork

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

Yeah, the C&P messed up the first time.

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

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)

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

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,")");

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

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

Mathematica, 45 43 bytes

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

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

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

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:

(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!

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.

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

Python 3, 40 chars

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

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

Ruby, 41 29 bytes

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

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

Thanks @ValueInk

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

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

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 (

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

Pyke, 9 bytes

\(JQl\)*+

Try it here!

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

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.

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

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

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!

Pyth - 9 bytes

+j\(Qsm\)

Try it online here.

><>, 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!

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

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.

Convex, 10 bytes

_'(*\,(')*

Try it online!

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

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

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

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.

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
                   }

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.

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.

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