text:
N(e(s(t))) a string
To "function nest" a string, you must:

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

Then, repeat this same step for every substring. So we get:
H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:
H(e(l(l(o( (w(o(r(l(d(!)))))))))))

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.
For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.
Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

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

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

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

Input:
a
Output:
a

Input:
42
Output:
4(2)

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

Ahem: Is this message anything to do with the challenge? :-)

TIL 42 = 8

What is maximum length for the input string? Incase of recursive methods

Is the output the execution of said function, or merely the string itself?

@nl-x The string itself.

Can you take input as an array of characters or must it be a string?

@kamoroso94 You may take the input and the output in any reasonable format. A list of characters seems perfectly reasonable to me.

So that's what Lisp code looks like

can the last character be "function nested" - e.g. can would hello -> h(e(l(l(o())))) be acceptable?

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.

That ~- trick is cool, I will need to remember that.

how does the ~-trick work ?

@ShadowFlame - makes the number negative and ~ bit flips it.  You can read a bit more about it on the tips page.

@ShadowFlame. The mechanics of it is as WheatWidard said. It works on systems that use twos-complement mode to store negative numbers (which is most systems nowadays).

Hail Python! Clever shit with the bit flips there.

@MadPhysicist With Python, it works always, because ~ is defined as -x-1

MS-DOS .com file, 30 bytes
0000   fc be 82 00 b4 02 ac 88 c2 cd 21 ac 3c 0d 74 0d
0010   b2 28 50 cd 21 5a e8 f0 ff b2 29 cd 21 c3

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

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

Since I can't find any actual documentation or satisfactory info: why call 0xfoff? The program is loaded into memory at address 0 as far as I can tell (or 0x100 on CP/M-DOS but these appear to be x86 instructions), why is recursiveFunction suddenly located at 0xffof? It appears to begin 9 bytes after the beginning of the program, and there is no virtualisation or metadata in the executable.

DOS loads .COM files to address 0x100 however this program would even run on ANY address: e8 f0 ff is a relative call instruction: It jumps to the address of the instruction following the call instruction minus 0x10.

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!

Nice trick with 1/s.

Super nice trick with ([c,...s]) you should write a tip

@edc65 Just for sake of clarity, this one was suggested by ETHproductions.

o well, someone has to write a tip anyway

@edc65 On it...

@edc65 its called "destructuring assignment" check https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

@jmingov thank you, I know. The point here is using DA to to slice a string in a very short way (very shorter than .slice)

... although you have to be careful, since it turns into an array.

@edc65 For reference, the tip can be found here. Feel free to suggest a way to improve it.

@ETHproductions Upvoted already - I was tracking you.

Brainfuck, 42 40 bytes
>+[-->+[<]>-]>+>>,.,[<+<.>>.,]<<+>[-<.>]

Try it online!
Ungolfed:
>+[-->+[<]>-]>+     # count to 40 (ASCII for open paren)
>>                  # move to the input holder
,.                  # input the first byte and output it
,                   # input the next byte
[                   # while it's not zero
  <+                # move to the input counter and increment it
  <.                # move to the open paren and output it
  >>.               # move to the input holder and output it
  ,                 # input the next byte
]
<<+                 # move to the open paren and increment it to a close
>                   # move to the input counter
[                   # while it's not zero
  -                 # decrement it
  <.                # move to the close paren and output it
  >                 # move to the input counter
]

There is usually a shorter way to get a constant than the obvious 2-factor multiplication.

Ah nice, thanks. This was my first BF submission (my first BF program at all, really) so I'm sure there are lots of other possible improvements too.

you got one pair of brackets to much!?

This puts an empty pair of parentheses after the last character of the string. I don't know if there's a way to avoid that without adding ",." before the loop and switching the output order inside the loop, which makes the program two bytes longer.

Ah bugger, you're right. I didn't read carefully enough and made the last letter a function call like the others.

05AB1E, 11 bytes
S'(ý¹g<')×J

Try it online!
Explanation:
S'(ý         join input by "("
    ¹g<      push length of input - 1, call it n
       ')×   push a string with char ")" n times
          J  concatenate

Brainfuck, 44 bytes
>+++++[-<++++++++>],.,[<.>.>+<,]<+>>[-<<.>>]

Reads a byte at a time, puts an open-paren before each one except the first, puts the same number of close-parens at the end.

+++++[->++++++++<],.,[>.>+<<.,]>+>[-<.>] is slightly shorter.

Haskell, 30 bytes
f[x]=[x]
f(a:b)=a:'(':f b++")"

Usage example: f "Nest a string" -> "N(e(s(t( (a( (s(t(r(i(n(g))))))))))))".
Take the next char, followed by a (, followed by a recursive call with all but the first char, followed by a ).

If we interpret the answers as Haskell, we can solve it with just f=Data.List.intersperse '$'!
That gives us f "Nest a string" -> "N$e$s$t$ $a$ $s$t$r$i$n$g".

Just wanted to let you know that @fornit  (he hasn't enough rep to comment) suggested to use f[]=[] as a base case instaed of your f[x]=[x]. I'm not familiar with Haskell so I don't know whether it's legit or not, I'll let you judge.

@Dada: that won't work, because it would put an additional () behind the last letter, e.g. f "abc" -> "a(b(c()))".

This also doesn’t handle empty input. The shortest correct version I could come up with is 44, with a different technique: f=(++).intersperse '('<*>drop 1.map(\_->')').

@JonPurdy: we don't have to handle empty input.  intersperse requires import Data.List for another 17 bytes.

@nimi: I missed that part—my bad. And apparently I need to have fewer default imports in my .ghci when golfing. Something resembling intersperse could be made from e.g. >>=(:"(") but it might not be worthwhile.

Jelly, 9 8 bytes
-1 byte thanks to @Dennis (use mould, ṁ, in place of length, L, and repeat, x)
j”(³”)ṁṖ

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

Btw, ³ actually causes Jelly to print the current return value, so you never have two lists of chars.

Alternate 8 byter

@lyxal Nice. I don't think Ø( existed back then.

Retina, 22 17 bytes
\1>`.
($&
T`(p`)_

Try it online!
Alternatively:
S_`
\`¶
(
T`(p`)_

Explanation
I always forget that it's possible to print stuff along the way instead of transforming everything into the final result and outputting it in one go...
\1>`.
($&

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

All that's left is to print the closing parentheses:
T`(p`)_

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

Dangit. So fast...

@mbomb007 ...and far from optimal. ;)

J, 13 bytes
(,'(',,&')')/

J executes from right-to-left so using the insert adverb /, a verb can be used to reduce the letters of the input string.
Usage
   f =: (,'(',,&')')/
   f 'Nest a string'
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))
   f 'foobar'
f(o(o(b(a(r)))))
   f '1234567890'
1(2(3(4(5(6(7(8(9(0)))))))))
   f 'code-golf'
c(o(d(e(-(g(o(l(f))))))))

You can observe the partial outputs between each reduction.
   |. f\. 'Hello'
o
l(o)
l(l(o))
e(l(l(o)))
H(e(l(l(o))))

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

><>, 19 18 bytes
io8i:&0(.')('o&!
o

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

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

C#, 32 bytes
F=s=>*s+++(0<*s?$"({F(s)})":"");

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

the definition should run as declared and counted

Java 7,81 79 bytes
Saved 1 byte.Thanks  to kevin.
String f(char[]a,String b,int l){return l<a.length?f(a,b+'('+a[l],++l)+')':b;}

Nice recursive approach. Shorter than the for-loop I was about to post. +1 Two things you can golf though: l!=a.length -> l<a.length and b=b+'('+a[l],++l)+')' -> b+="("+a[l],++l)+")" (-2 bytes)

@KevinCruijssen b+="("+a[l],++l)+")" gives you 144141148))),and BTW b+"("+a[l],++l)+")" is correct. and this was very silly mistake of mine(!=).

No, b+='('+a[l],++l)+')' gives 144141148, but b+="("+a[l],++l)+")" doesn't. The parentheses are surrounded by String-quotes instead of char-quotes.

I post my version (82 bytes in Java 7) using only the input String as parameter. Verbose but not that bad ;) If you find something to change : http://codegolf.stackexchange.com/a/96745/59739

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

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

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

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!

PowerShell v2+, 46 bytes
param([char[]]$a)($a-join'(')+')'*($a.count-1)

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

APL, 19 bytes
{∊('(',¨⍵),')'⍴⍨⍴⍵}

Explanation:
{
  ('(',¨⍵)          ⍝ join a ( to each character in ⍵
          ,')'⍴⍨⍴⍵  ⍝ for each character in ⍵, add an ) to the end
 ∊                  ⍝ flatten the list
                   }

Alternative solution, also 19 bytes:
{⊃{∊'('⍺⍵')'}/⍵,⊂⍬}

Explanation:
{
              ⍵,⊂⍬  ⍝ add an empty list behind ⍵ (as a base case)
  {         }/      ⍝ reduce with this function:
    '('⍺⍵')'        ⍝   put braces around input
   ∊                ⍝   flatten the list
 ⊃                  ⍝ take first item from resulting list
                   }

Where do you buy the keyboards for such a language!!!

@RonanDejhero Perhaps just remapping keys using cltr, shift, alt, capslock, numlock etc.

It can be shortened using trains, I guess:
(∊'('∘,¨,')'⍴⍨⍴)
But doesn't this add an extra couple of brackets?

Both solutions and also the one suggested by @Popov put an extra set of brackets around the output required in the question.

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

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

GNU sed, 37 35 31 bytes (30 +1 for -r argument)
Pure linux sed solution
:;s/([^(])([^()].*)$/\1(\2)/;t

Naming the subsitution :; then calling it recursively with t
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

Add parenthesis around the second group \1 ( \2 )

Edit: Thanks to @manatwork for helping removing 4 characters!
Online tester

Using only 2 groups seems to be enough. Capture the 2nd and 3rd together.

Oh, and sorry, but command line options necessary to change the interpreter's default behavior for your code to work, have to be included in the size count. The barely necessary -e to pass the code to the interpreter is for free. (Ok, sed is happy without it too.) So for sed -re '…' you count +1.

Blank labels are a GNU sed feature/bug, so maybe the title should be GNU sed.

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

You can save two bytes by using <?= instead of echo  and another one if you set $s to the result of the str_split call instead of $argv[1], and then use count($s) instead of strlen($s)

63 bytes: <?=str_pad(join("(",$s=str_split($argv[1])),count($s)*3-2,")");- wordwrap would beat the split/join combination, but unfortunately fails if the input contains whitespace.

@Titus nice alternative Thank You

Ruby, 27 bytes
->s{s.chars*?(+?)*~-s.size}

Explanation
->s{                       # Declare anonymous lambda taking argument s
    s.chars                # Get the array of chars representing s
           *?(             # Join the elements back into a string using "("s as separators
              +?)*~-s.size # Append (s.size - 1) ")"s to the end

Perl, 25 bytes
Thanks to @Ton Hospel for golfing out 4 bytes.
24 bytes of code + -F.
$"="(";say"@F".")"x$#F

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

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

Another interesting way (a little bit longer though : 28 bytes) :
Thanks to Ton Hospel once again for helping me getting this one right.
#!/usr/bin/perl -p
s/.(?=.)/s%\Q$'%($&)%/reg

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

You don't need the "" after the -F. You also don't need the -l if you demand the input string is entered without final newline: echo -n Hello | program

@TonHospel Right, I forgot (or didn't know, not sure) about that behavious of -F, thanks. (I was wondering how to get the input without the final newline, thanks for that too)

perl -F -E '$"="(";say"@F".")"x$#F'

You can get your other idea working with something like s/.(?=.)/s%$'%($&)%/reg, but it of course doesn't support strings containing regex metacharacters

@TonHospel Thanks a lot for all of that! (About the second one, I added \Q to support regex metacharacters) :-)

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.

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

Vim, 17 bytes
$qqha(<Esc>A)<Esc>%h@qq@q
Goes from end to beginning, because otherwise you trip over the )s you've already written. Uses ha instead of i to fail when it reaches the beginning.
Usually, you wouldn't do two separate inserts like this; you'd do something like C()<Esc>P to save a stroke. But the positioning doesn't work as well this time.

You can use the <End> key in insert mode instead of leaving insert mode and doing A

@BlackCap That's not a byte. I'd need to count strokes instead of bytes. (And Vimgolf is a better game when you ban cursor keys, though the difference here is trivial.)

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

Java 82 81
Thanks to Olivier Grégoire for the correction leading to 1byte less.
Solution
I forced myself in using a String a not a char[] so this is a bit more verbose :/
String n(String s){return s.length()>1?s.charAt(0)+"("+n(s.substring(1))+")":s;}

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

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

For Java 7, did you notice that the last character is duplicated? For Java 8, it won't compile and work because you have to define a recursive function like this: n=s->...n.apply(...) instead of s->...n(...), also there are some other issues which make your answer don't work.

Thanks, indeed I missed that ... I just made the correction and gain a byte, thanks :) . I removed the Java 8 part since I can't test it here and don't have enought experience to do it blindly ;)

Well, actually a recursive function can't work in Java 8. You always get a "self-reference in intializer" error.

@OlivierGrégoire Never used Lambda for complex code, mainly for small validation process. But thanks for the info, I will dig into this.

Factor, 81 bytes
[ [ >array [ 1string ] map "("join ] [ length 1 - [ 40 ] replicate >string ] bi ]

Convex, 10 bytes
_'(*\,(')*

Try it online!

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 (

Beat me to it. +1

Hmm. I thought that reusing the 40 to avoid pushing a large integer again would save you a lot of bytes, but the best I can come up with is {({}<><(((((()()){}()){}){}){})>)<>}<>({}<(({})<>())><>)([]){({}[()()]<(<>({})<>)>)}{}{}{({}<>)<>}<>{} which is two bytes longer...

Thanks for giving me the idea to reuse the 40. I got it down to 95+3. Why is it 3 bytes for -a in Brain-Flak anyway?

Oh, nice work! The +3 bytes is standard for special command line flags. Which is unfortunate, but something I can put up with. I've actually been thinking of ways to shorten this, but I'm not exactly sure how yet.

Isn't it normally 2 bytes? one for the - and one for the flag? You could have a flag for normal execution like Perl does with -e. That way it would only be 1 extra byte.

Well, there's also one for the space (which isn't necessary for perl). But the -e flag is a good idea, although I don't know exactly how it would work. Do you want to talk about it more in the brain-flak room?

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

Row by row

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

Try it online!

Perl, 36 bytes (34 + 2 for -lpflag)
Thanks to Dada for pointing out a bug and saving one byte (in total)!
Splits the string into an array, then joins it with the (delimiter. We directly add the closing )since lengthreturns the length of the string before the join.
$_=(join"(",split//).")"x(y///c-1)

Try it here!

Sure you don't need -l flag? I doesn't seem to work when I try it... Or maybe I missed something?

Also, you can write y///c-1 instead of -1+length to save 2 bytes.

@Dada indeed, -l is needed when you run this with the terminal. I'm always doing these things on Ideone and it's not needed there... Editing! (and thanks for the tip!)

You could also do $_=(join"(",@a=split//).")"x(@a-1) which is a bit more verbose and the same number of bytes as the y///c-1. Or well, depends on the definition of verbose.

You can again drop the -l option by demanding that the input string is entered without final newline, echo -n Hello | program

Dyalog APL, 14 bytes
⊃{⍺,1⌽')(',⍵}/
this is an atop of ⊃ and { }/
⊃ (get first element) will be applied after { }/ (reduction of a lambda)
⍺,1⌽')(',⍵ - the left argument (⍺) concatenated with (,) the rotation by one element to the left (1⌽) of the string ')(' concatenated with (,) the right argument (⍵)
reduction in APL folds from right to left, as required here

Stax, 8 6 bytes
-2 thanks to @recursive!
çΔ \Γ]

Run and debug it at staxlang.xyz!
Unpacked (7 bytes) and explanation:
Mrks:{+
M          Transpose array. This turns a string into an array of length-1 strings.
 r         Reverse string.
  k        Fold array using the rest of the program as a block:
   s         Swap. This puts the accumulator on top of the current element.
    :{       Wrap in parentheses.
      +      Concatenate.
           Implicit print at end of program!

If you transpose the input string, you can get rid of the stringifications, and pack down to 6.  Mrks:{+

@recursive Ah. That's what I was looking for. Definitely beats {]m for the same functionality!

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

SWI-Prolog, 82 bytes
q([H],[H]).
q([H|T],[H,40|S]):-q(T,R),append(R,[41],S).
X*Y:-q(X,Z),atom_codes(Y,Z).

Called like: `Hello World!`*X.
Online interpreter

Worth mentioning that this is shorter but can't handle symbols correctly.

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

C, 102 89 bytes
Maybe this can be golfed more? I'm just happy to answer in C! :D
i=0,j=0;f(char*a){while(*a)putchar(*a),*++a?putchar(40),i++:0;while(j<i)putchar(41),j++;}

79 bytes

@ceilingcat  braver than me.

Perl 5, 44 33 bytes (31 + 1 for -l + 1 for -p)
saved 11 bytes thanks to Dada
s/([\w ])([\w ]+)/$1($2)/&&redo

Can be run from the command line with the -p and -e options.
$ perl -ple 's/([\w ])([\w ]+)/$1($2)/&&redo' <<< 'Hello'

Output:
H(e(l(l(o))))

You can use -l instead of chomp to save 5 bytes. Also, since -p surround the code with a while, you can do s/../../&&redo instead of 0while s/../../. As it happens, this regex is shorter : s/([\w ])([\w ]+)/$1($2)/.

Another thing : usually, when you really need to chomp, you can chop instead to save one byte ;)

@Dada thanks, didn't think about the redo and got caught up building a complicated regex. I need to understand that golf is not obfuscation. ;)

You code wasn't that bad! It just takes time and practice! And even after that, Ton Hospel will always find a shorter way than everybody else! ;-)

thanks @dada. I borrowed the python code and made it shorter in Perl in another answer

You don't need the -l if you demand the input string is entered without final newline: echo -n Hello | program.

You are supposed to support all printable ASCII so you need [^()] instead of [\w ]. The first one in fact only needs [^(]

Mathematica, 35 27 bytes bytes
Saved 8 bytes on adding the appropriate number of ")" to the end thanks to alephalpha
#~Riffle~"("<>Most[0#+")"]&

Input is a list of characters. Riffles "(" between each character, then adds that many ")" minus 1 to the end. Specifically, multiplies the input by 0, adds ")" and then takes Most of the list.
e.g.
#~Riffle~"("<>Most[0#+")"]&[{"H","e","l","l","o"}]

{"H","e","l","l","o"}~Riffle~"("<>Most[0{"H","e","l","l","o"}+")"]

{"H","(","e","(","l","(","l","(","o"}<>Most[{0,0,0,0,0}+")"]

{"H","(","e","(","l","(","l","(","o"}<>Most[{")",")",")",")",")"}]

{"H","(","e","(","l","(","l","(","o"}<>{")",")",")",")"}

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

#~Riffle~"("<>Most[0#+")"]&

Poetic, 244 bytes
life is a quest,i say
i choose a fun course to cross
i cant say quite if survival excites
i say i am laughing
i create a way i relive a feeling
exile is torture,i say
i am thankful,of course,to say i adore u
i desire a wedding where i said i do

Try it online!
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.
The point of the language is to allow for programs to be written in free-verse poetry.

05AB1E, 11 10 bytes
-1 byte thanks to @Kevin Cruijssen
S'(ý?¨v')?

Try it online!
Explanation
             #implicit input
S            #cast input to list
   ý         #list join
 '(          #( character
    ?        #print list without a newline
      v      #foreach item in
     ¨       #first input[0:-1]
       ')?   #print ) without a newline

Welcome to the site!

thank you! @WheatWizard

You can remove the ¹ to save a byte. It will use the input implicitly again, since the stack is empty. :)

Vyxal, 7 bytes
÷!‹(øb+

Try it Online!
÷       # Push each to the stack
 !‹(    # (input-1) times...
    øb  # Parenthesise what's currently on the stack
      + # and append it

gamed on

@lyxal Not anymore ;)

Turtlèd, 25 27 bytes
(original didn't work for single char inputs ;_;)
This is what Turtlèd ended up being for even though it as originally ascii art stuff.
!-l[*+.r'(r_]l-_[*-')r_]"  [2 trailing spaces]

Try it online!
Explanation:
put the input on to the cells with ( after each char

!                        Take a string as input
 -                       decrement the string pointer, so it points at last char
  l                      move left
   [*       ]            while the current cell is not *
     +.r                 increment string pointer and write the pointed char, move right
        '(r              write (, move right
           _             write * if pointed char is last char, else " "

Write the terminating parens, the first one overwriting the last open paren

             l-           move left, decrement string pointer
               _          write * if pointed char is last char, else " "
                [*     ]  while the current cell is not *
                  -')r    decrement string pointer, write ), move right
                      _   write * if pointed char is last char, else " "

                        "[2 spaces]  Remove the last *, or two *s if input is one char

Zsh, 36 Bytes
z=${1:1};<<<${1[1]}${z///(}${z//?/)}

This should be possible in 34 bytes, but zsh syntax is inconsistent. $a[1] will return the first character of the string $a, but $1[1] returns the entire contents of $1 plus the string "[1]". I'd love to know if this is intended behavior, or just on a long list of zsh documentation not covering edge cases.
The logic used is

Assign all but the first character of the first argument to a variable z
Print the first character of the input
Print z, with "the empty string replaced with (" which actually places a ( before each character of z
Print z, with all of the characters replaced with )

I don't think its golfable much farther from here, even though I how many characters it takes to just split the first character from the rest of the string. There is probably a more efficient "logic" though, I just couldn't find one that synergizes with zsh or bash.
Speaking of bash, this doesn't work because the cute trick with sed-style replacing the empty string does not do anything in bash. I will edit with a solution that is better designed for bash-compatible syntax.

Really cool solution but doesn't handle the single-character input properly. Adjusted solution for 55 bytes.
z=${1:1};(($#1==1))&&<<<$1||<<<${1[1]}${z///(}${z//?/)}

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

why not change $s[1]>"" into just $s[1]? 3 chars less.

@nl-x because the 0 character evaluates to false

@nl-x ... but I learned something just as long in the meantime.

Please do explain what you did there...

@nl-x I messed it up. I intended a shorter check on the second character using bitwise arithmetics, but checked the string for emptiness instead. Rolled back.

CJam, 12 11 bytes
One byte saved by Martin Ender.
q_'(*\,(')*

Try it online

You can save a byte by avoiding the second \: q_'(*\,(')*

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

Puts a parenthesis after each characters in y.
Puts a parenthesis for each characters in z.
Print x and z truncated of one character.

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

Pyth, 10 characters
+j\(Q*\)tl

Try it online!
Joins the input on (, and appends length - 1 closing parens afterwards.

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

Could be shorter

I think you meant (s:String)=>s.mkString("(")+")"*s.length (40 bytes) (no need for match case here)

Also - I think it's not correct. You'll need *(s.length-1)

Actually, 10 bytes
lD')*ß'(j+

Try it online!
Explanation:
lD')*ß'(j+
lD')*       ")"*(len(input)-1)
     ß'(j   insert a "(" between every pair of characters in the input
         +  append the closing parens

V, 9 bytes
$òys$)hhl

Try it online!

JavaScript, 36 bytes
([...v])=>v.join`(`+v.fill``.join`)`

I can't seem to beat the top score of 34 bytes, but I thought I would share my different approach.

Apparently OP allowed (in his comments in 2017) list/array of characters as input. So your answer could be 29 bytes ?

Ruby, 41 29 bytes
->s{s.split("").join(?()+?)*(s.length-1)}
->s{(s.chars*?()+?)*~-s.size}

Thanks @ValueInk

chars is more efficient than split, and I believe you want s.length-1

size is more efficient than length, and multiplying an array by a string does an implicit join. And finally, (x-1) can be substituted to ~-x. Combining with Lee W suggestions, you end up with ->s{(s.chars*?()+?)*~-s.size} for 29 bytes!

And then I realize that these standard optimizations causes it to be exactly like @m-chrzan's answer, and now this is a tad awkward

Lua, 88 bytes
Probably not nearly as short as it could be.
x=""y=...for i=1,#y-1 do x=x..y:sub(i,i).."("end print(x..y:sub(-1,-1)..(")"):rep(#y-1))

Takes input from the command line.

Here's even better! y=...print(y:gsub('.','%1(',#y-1)..(')'):rep(#y-1)) 51 bytes I also made variations for repeat until and while end but they were longer than yours even though as minified as possible.

@ascx In here, you're not allowed to edit his answer just to golf it further. Let the author did that.

@ascx http://meta.codegolf.stackexchange.com/a/1619/46245

Pyth - 9 bytes
+j\(Qsm\)

Try it online here.

The output has one )  too many.

Use +j\(Qstm\) instead.

Mathematica, 45 43 bytes
#2<>"("<>#<>")"&~Fold~Reverse@Characters@#&

You can use # instead of #1. And infix notation ~Fold~ should also work.

QBIC, 64 bytes
Way too large. Posted as an incentive to get my butt moving again on the QBIC project.
;_LA|[a-1|Z=Z+$mid$|(A,b,1)+@(|]Z=Z+$right$|(A,1)[a-1|Z=Z+@)|]?Z

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

EDIT: Got my butt moving. Now in 48 bytes:
_L;|[a-1|Z=Z+_sA,b,1|+@(`]Z=Z+_sA,-1|[a-1|Z=Z+@)

Huh. QBIC looks interesting. Is there a github project I could follow? Or a README describing what it is?

@DrMcMoylex I swear, the day I figure out how Github works ... The project lives in a shared folder on a Google Drive, link in the header. Some info o getting started here and here.

Why is QBIC not on TIO?

@MDXF Well, QBIC code is converted into QBasic code, which is run in Dosbox. I do not believe that such an environment can be easily set up for use on the web... I am taking suggestions however :)

@steenbergh Ah, that's true. I'm actually looking into ways to get QBasic / ABASIC / Applesoft Basic onto TIO. Right now it's looking like I'm going to need to write my own interpreters. >.<

@MDXF The closest I've come to a web-interpreter yet is an Emscripten port of Dosbox someone made. You can add QBasic to its filesystem and let JS run the whole thing, but it's huge, slow and has drawbacks on interactivity.

@steenbergh Actually, QBasic is on repl.it, and it may be added to TIO soon.

@MDXF The implementation at repl.it seems to be a bit lacking...

@steenbergh ....indeed.

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!

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!

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

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

Ugh, that builtin. Nice job :P

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!

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 is shorter than add1.

Python 3, 40 chars
s=input()
print("(".join(s)+len(s)*")")

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

Groovy, 38 36 Bytes thanks to @manatwork
{it.reverse().inject{r,i->i+"($r)"}}

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

I think your code was destroyed on copy paste, as is neither functional and is far from your byte count. BTW, no need for braces around simple variables in expansion.

@manatwork was missing a brace, the braces are for string interpolation and you're right I effed the byte-count, forgot it needed reverse.

I use http://lettercount.com for groovy byte count, NO IDEA what was going on. I thought 68 seemed high...

Cool. But you still have extra braces in interpolation: "(${r})" → "($r)". At least Groovy 2.4.5 is happy without them too.

@manatwork most of my experience is with Groovy on Grails and $ notation isn't accepted in views AFAIK.

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

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

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

This doesn't work. You can't have if statements in one line. SyntaxError

I just put in on the one line to show it concisely without whitespace. You actually run the ungolfed version

Sorry, @bioweasel, but the spaces needed for the code to run have to be counted. Better refactor it to have a single statement inside the function: def c(s):return s if(len(s)==1)else s[0]+"("+c(s[1:])+")".

Ah, gotcha. Sorry, this is my first time and I wasn't quite sure on the rules 100%, especially with Python and the whitespace

You could use that s[1:] syntax in the condition too: def c(s):return s[0]+"("+c(s[1:])+")"if s[1:]else s.

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

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

If a function entry needs to call itself, you must include the assignment (i.e. F=) in the byte count. Also, I think you can do s at the end instead of s[0], as the string's length is already 1.

ups, I actually had it like that but forgot to copy it.. thanks!

Quite similar to bioweasel's Python solution.

Indeed, didn't see his solution..

Possible 48 bytes.

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.

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

That's some very nice golfing! :-)

You don't need the -l if you demand the input string is entered without final newline: echo -n Hello | program

Pyke, 9 bytes
\(JQl\)*+

Try it here!

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.

This prints one extra close paren each time.  Try ~-len(x) rather than len(x)

@WheatWizard Thank you, I don't know how I missed that.

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

I guess you could merge function definition and let to (defn n[[f & r]](if f(str f(if r(str\((n r)\))))) :)

@NikoNyrh You're right! I hate deconstructing in the parameter list in real code, but that certainly helps here. Thanks!

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.

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

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!

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.

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.

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)

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!

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
(＊；Ｌ╷)×＋

Try it here!

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

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

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.

Being able to test a submission on TIO is not a requirement, so your MATLAB answer is just fine. It's preferable to post different solutions in different answers though, so they can be voted on independently.

Octave implementation of fold()

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

Just for fun: achieves the same bytecount using non-extended Keg.

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!

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!

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.

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

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.

MAWP, 33 bytes
%|_!1A[1A~;85W;~]~;1A[1A~85W1M;~]

Try it!

Hm, I thought I did this correctly. Can someone tell me what's wrong with the program?

Nothing's wrong... It's most likely an accidental downvote. I know I've done it before around here! Fwiw, it wasn't me this time.

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

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.

Python 3, 51
Just a simple recursive function.
lambda s:s if len(s)<2else s[0]+"("+nest(s[1:])+")"

Try it online!

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

KamilaLisp v0.2, 32 (APL SBCS)
$(⌿.← \λ(x y)\⍫∊ "{?y}({?x})")∘⌽

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

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

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

Heh... I spent a while scratching my head about how this worked until I remembered that ' is for characters, not strings... ;^) Anyway, here's 12 bytes.

@DLosc thanks, updated.

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)

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)

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

It might need an extra B extends""?B:clause, haven’t tested it

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

Testable on http://rextester.com/live/SAXFO71660

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

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.

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

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

ioiEH')('o$!

@JoKing well now I feel inadequate /s

Well, when creating a Gol><> answer you need to check if there's an existing ><> answer you can adapt ;)

Welcome to PPCG! looks like you have too many parentheses: there should be no opening parenthese after the last letter of the string.

Japt, 11 bytes
¬q'( +UÅî')

Try it

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!

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

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


text:
Tips for golfing in Starry
What general tips do you have for golfing in Starry? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Starry (e.g. "remove comments" is not an answer).
Please post one tip per answer.

Related.

There's a book on esolangs -- how interesting!

Use dup and add for large numbers
If you need to produce a big but reasonable number which is a multiple of 2 (and in some cases, even not a multiple), you can push half the number and end with  +* (dup and add) instead of pushing the whole number. The threshold for this is 8 and above.
As mentioned, sometimes you can double, then subtract one (threshold 27), and with multiples of higher 2 powers it can be repeated to gain greater numbers.
Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Find the Centroid of a Polygon
From Wikipedia:

The centroid of a non-self-intersecting closed polygon
  defined by n vertices (x0,y0),
  (x1,y1), ...,
  (xn−1,yn−1) is the point (Cx,
  Cy), where

and where A is the polygon's signed area,

In these formulas, the vertices are assumed to be numbered in order of
  their occurrence along the polygon's perimeter. Furthermore, the
  vertex ( xn, yn ) is assumed to be the same as
  ( x0, y0 ), meaning i + 1 on the last case
  must loop around to i = 0. Note that if the points are numbered in
  clockwise order the area A, computed as above, will have a negative
  sign; but the centroid coordinates will be correct even in this case.

Given a list of vertices in order (either clockwise, or counter-clockwise), find the centroid of the non-self-intersecting closed polygon represented by the vertices.

If it helps, you may assume input to be only CW, or only CCW. Say so in your answer if you require this.

The coordinates are not required to be integers, and may contain negative numbers.
Input will always be valid and contain at least three vertices.
Inputs only need to be handled that fit in your language's native floating point data type.
You may assume that input numbers will always contain a decimal point.
You may assume that input integers end in . or .0.
You may use complex numbers for input.
Output should be accurate to the nearest thousandth.

Examples
[(0.,0.), (1.,0.), (1.,1.), (0.,1.)]        -> (0.5, 0.5)
[(-15.21,0.8), (10.1,-0.3), (-0.07,23.55)]  -> -1.727 8.017
[(-39.00,-55.94), (-56.08,-4.73), (-72.64,12.12), (-31.04,53.58), (-30.36,28.29), (17.96,59.17), (0.00,0.00), (10.00,0.00), (20.00,0.00), (148.63,114.32), (8.06,-41.04), (-41.25,34.43)]   -> 5.80104769975, 15.0673812762

Too see each polygon on a coordinate plane, paste the coordinates without the square brackets in the "Edit" menu of this page.
I confirmed my results using this Polygon Centroid Point Calculator, which is awful. I couldn't find one that you can input all vertices at once, or that didn't try to erase your - sign when you type it first. I'll post my Python solution for your use after people have had a chance to answer.

The much simpler technique of averaging all x's and y's works for the first two sets, but not the third. I wonder what makes the difference...

@ETHproductions The third polygon is not convex.

@ETHproductions If you approximate a circle with a polygon, you can move the average point arbitrary close to a point on the circle by using more points close to that point, while nearly not effecting the centroid and keeping the polygon convex.

Interesting, thanks for the info!

@ETHproductions Actually convexity is not the reason. Averaging all xs and ys puts all the weight in the vertices instead of distributed over the body. The first one happen to work because it is regular, so both methods end up at the symmetry center. The second one works because for triangles both methods lead to the same point.

Can we use complex numbers for I/O?

@xnor I think it makes sense to allow that, since real+imag corresponds to x,y. If you've already done it with x,y, you could post both answers, so we can see how much it saves.

@mbomb007 Is input format supposed to strictly follow the example or can we e.g. use two separate lists (R-vector in my case) for x and y or a function that takes two lists e.g. f(x,y). Also can output be separated by newline?

@Billywob Output is not strict, so that's fine. For input, I think it needs to be pairwise x,y vertices, rather than the transposed form.

Jelly, 25 24 22 21 18 bytes
S×3÷@×"
ṙ-żµÆḊçS€S

Applies the formula shown in the problem.
Saved 3 bytes with help from @Jonathan Allan.
Try it online! or Verify all test cases.
Explanation
S×3÷@×"  Helper link. Input: determinants on LHS, sum of pairs on RHS
S        Sum the determinants
 ×3      Multiply by 3
     ×"  Vectorized multiply between determinants and sums
   ÷@    Divide that by the determinant sum multipled by 3 and return

ṙ-żµÆḊçS€S  Main link. Input: 2d list of points
ṙ-          Rotate the list of points by 1 to the right
  ż         Interleave those with the original points
            This creates all overlapping slices of length 2
   µ        Start new monadic chain
    ÆḊ      Get the determinant of each slice
       S€   Get the sum of each slice (sum of pairs of points)
      ç     Call the helper link
         S  Sum and return

You can replace ṁL‘$ṡ2 with ṙ1ż@ or żṙ1$

@JonathanAllan Thanks, also I can rotate by ṙ-ż to avoid the swap and save another byte

Oh yes of course!

Mathematica, 23 bytes
RegionCentroid@*Polygon

Take THAT, Jelly!
Edit: One does not simply beat Jelly...
Explanation
Polygon

Generate a polygon with vertices at the points specified.
RegionCentroid

Find the centroid of the polygon.

Well you beat me, but there's probably a shorter way than what I have, I don't have a complete understanding of Jelly yet

@miles aw... :(

J, 29 bytes
2+/@(+/\(*%3*1#.])-/ .*\)],{.

Applies the formula shown in the problem.
Usage
   f =: 2+/@(+/\(*%3*1#.])-/ .*\)],{.
   f 0 0 , 1 0 , 1 1 ,: 0 1
0.5 0.5
   f _15.21 0.8 , 10.1 _0.3 ,: _0.07 23.55
_1.72667 8.01667
   f _39 _55.94 , _56.08 _4.73 , _72.64 12.12 , _31.04 53.58 , _30.36 28.29 , 17.96 59.17 , 0 0 , 10 0 , 20 0 , 148.63 114.32 , 8.06 _41.04 ,: _41.25 34.43
5.80105 15.0674

Explanation
2+/@(+/\(*%3*1#.])-/ .*\)],{.  Input: 2d array of points P [[x1 y1] [x2 y2] ...]
                           {.  Head of P
                         ]     Get P
                          ,    Join, makes the end cycle back to the front
2                              The constant 2
2                      \       For each pair of points
                  -/ .*        Take the determinant
2    +/\                       Sum each pair of points
         *                     Multiply the sum of each pair by its determinant
          %                    Divide each by
             1#.]              The sum of the determinants
           3*                  Multiplied by 3
 +/@                           Sum and return

Maxima, 124 118 116 112 106 byte
f(l):=(l:endcons(l[1],l),l:sum([3,l[i-1]+l[i]]*determinant(matrix(l[i-1],l[i])),i,2,length(l)),l[2]/l[1]);

I'm not experienced with Maxima, so any hints are welcome.
Usage:
(%i6) f([[-15.21,0.8], [10.1,-0.3], [-0.07,23.55]]);
(%o6)              [- 1.726666666666668, 8.016666666666668]

Racket 420 bytes
(let*((lr list-ref)(getx(lambda(i)(lr(lr l i)0)))(gety(lambda(i)(lr(lr l i)1)))(n(length l))(j(λ(i)(if(= i(sub1 n))0(add1 i))))
(A(/(for/sum((i n))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i))))2))
(cx(/(for/sum((i n))(*(+(getx i)(getx(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A)))
(cy(/(for/sum((i n))(*(+(gety i)(gety(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A))))
(list cx cy))

Ungolfed:
(define(f l)
  (let* ((lr list-ref)
         (getx (lambda(i)(lr (lr l i)0)))
         (gety (lambda(i)(lr (lr l i)1)))
         (n (length l))
         (j (lambda(i) (if (= i (sub1 n)) 0 (add1 i))))
         (A (/(for/sum ((i n))
                (-(* (getx i) (gety (j i)))
                  (* (getx (j i)) (gety i))))
              2))
         (cx (/(for/sum ((i n))
                 (*(+(getx i)(getx (j i)))
                   (-(*(getx i)(gety (j i)))
                     (*(getx (j i))(gety i)))))
               (* 6 A)))
         (cy (/(for/sum ((i n))
                 (*(+(gety i)(gety (j i)))
                   (-(*(getx i)(gety (j i)))
                     (*(getx (j i))(gety i)))))
               (* 6 A))))
    (list cx cy)))

Testing:
(f '[(-15.21 0.8)  (10.1 -0.3)  (-0.07 23.55)] )
(f '[(-39.00 -55.94)  (-56.08 -4.73)  (-72.64 12.12)  (-31.04 53.58)
     (-30.36 28.29)  (17.96 59.17)  (0.00 0.00)  (10.00 0.00)
     (20.00 0.00) (148.63 114.32)  (8.06 -41.04)  (-41.25 34.43)])

Output:
'(-1.7266666666666677 8.01666666666667)
'(5.8010476997538465 15.067381276150996)

R, 129 127 bytes
function(l){s=sapply;x=s(l,`[`,1);y=s(l,`[`,2);X=c(x[-1],x[1]);Y=c(y[-1],y[1]);p=x*Y-X*y;c(sum((x+X)*p),sum((y+Y)*p))/sum(p)/3}

Unnamed function that take an R-list of tuples as input. The named equivalent can be called using e.g.:
f(list(c(-15.21,0.8),c(10.1,-0.3),c(-0.07,23.55)))

Ungolfed and explained
f=function(l){s=sapply;                           # Alias for sapply
              x=s(l,`[`,1);                       # Split list of tuples into vector of first elements
              y=s(l,`[`,2);                       # =||= but for second element
              X=c(x[-1],x[1]);                    # Generate a vector for x(i+1)
              Y=c(y[-1],y[1]);                    # Generate a vector for y(i+1)
              p=x*Y-X*y;                          # Calculate the outer product used in both A, Cx and Cy
              c(sum((x+X)*p),sum((y+Y)*p))/sum(p)/3    # See post for explanation
}

The final step (c(sum((x+X)*p),sum((y+Y)*p))/sum(p)*2/6) is a vectorized way of calculating both Cx and Cy. The sum in the formulas for Cx and Cy are stored in a vector and consequently divided by the "sum in A" *2/6. E.g.:
(SUMinCx, SUMinCy) / SUMinA / 3

, and then implicitly printed.
Try it on R-fiddle

*2/6 could probably be /3?

@mbomb007 It's so painstakingly obvious, I guess I got caught up in golfing the other part. /shrug

Elegant, I like your use of sapply to deal with those lists! There could be scope for golfing here, I'm not sure how flexible the allowable input is. If you're allowed to input just a sequence of coordinates, like c(-15.21,0.8,10.1,-0.3,-0.07,23.55), then you can save 17 bytes by replacing the first lines of your function with y=l[s<-seq(2,sum(1|l),2)];x=l[-s];. That is, setting y to be every even-indexed element of l, and x to be every odd-indexed element.

Even better, though, would be if we can input a matrix (or array), like matrix(c(-15.21,0.8,10.1,-0.3,-0.07,23.55),2), as then the beginning of your function can be x=l[1,];y=l[2,];, which saves 35 bytes. (The input matrix could be transposed, in which case x=l[,1];y=l[,2];.) Of course, the easiest solution of all is if the x and y points are just input as separate vectors, function(x,y), but I don't think that's allowed...

@rturnbull I asked OP in comments and he specifically wanted a list of tuples (very inconvenient in R of course) so I don't think the matrix approach is allowed. And even if it was, the input would have to be the vector part (i.e. c(...)) and the matrix conversion would have to be done inside the function.

@rturnbull I.e. m=matrix(l,2);x=m[1,];y=m[2,]; would be shorter if a vector instead of a list was allowed.

Ah, too bad. The Jelly and J solutions use 2d arrays, so maybe the matrix approach is feasible? That is, input an entire pre-formatted matrix? Anyway, regardless of the input, your solution is really neat :-)

JavaScript (ES6), 102
Straight implementation of the formula
l=>[...l,l[0]].map(([x,y],i)=>(i?(a+=w=t*y-x*u,X+=(t+x)*w,Y+=(u+y)*w):X=Y=a=0,t=x,u=y))&&[X/3/a,Y/3/a]

Test

f=
l=>[...l,l[0]].map(([x,y],i)=>(i?(a+=w=t*y-x*u,X+=(t+x)*w,Y+=(u+y)*w):X=Y=a=0,t=x,u=y))&&[X/3/a,Y/3/a]

function go()
{
  var c=[],cx,cy;
  // build coordinates array
  I.value.match(/-?[\d.]+/g).map((v,i)=>i&1?t[1]=+v:c.push(t=[+v]));
  console.log(c+''),
  [cx,cy]=f(c);
  O.textContent='CX:'+cx+' CY:'+cy;
  // try to display the polygon
  var mx=Math.max(...c.map(v=>v[0])),
    nx=Math.min(...c.map(v=>v[0])),
    my=Math.max(...c.map(v=>v[1])),
    ny=Math.min(...c.map(v=>v[1])),
    dx=mx-nx, dy=my-ny,
    ctx=C.getContext("2d"),
    cw=C.width, ch=C.height,
    fx=(mx-nx)/cw, fy=(my-ny)/ch, fs=Math.max(fx,fy)
  C.width=cw
  ctx.setTransform(1,0,0,1,0,0);
  ctx.beginPath();
  c.forEach(([x,y],i)=>ctx.lineTo((x-nx)/fs,(y-ny)/fs));
  ctx.closePath();
  ctx.stroke();
  ctx.fillStyle='#ff0000';
  ctx.fillRect((cx-nx)/fs-2,(cy-ny)/fs-2,5,5);
}
go()
#I { width:90% }
#C { width:90%; height:200px;}
<input id=I value='[[-15.21,0.8], [10.1,-0.3], [-0.07,23.55]]'>
<button onclick='go()'>GO</button>

<canvas id=C></canvas>

Python, 156 127 bytes
def f(p):n=len(p);p=p+p[:1];i=s=0;exec'd=(p[i].conjugate()*p[i+1]).imag;s+=d;p[i]=(p[i]+p[i+1])*d;i+=1;'*n;print sum(p[:n])/s/3

Ungolfed:
def f(points):
  n = len(points)
  points = points + [points[0]]
  determinantSum = 0
  for i in range(n):
    determinant = (points[i].conjugate() * points[i+1]).imag
    determinantSum += determinant
    points[i] = (points[i] + points[i+1]) * determinant
  print sum(points[:n]) / determinantSum / 3

Ideone it.
This takes each pair of points [x, y] as a complex number x + y*j, and outputs the resulting centroid as a complex number in the same format.
For the pair of points [a, b] and [c, d], the value a*d - b*c which is needed for each pair of points can be computed from the determinant of the matrix
| a b |
| c d |

Using complex arithmetic, the complex values a + b*j and c + d*j can be used as
conjugate(a + b*j) * (c + d*j)
(a - b*j) * (c + d*j)
(a*c + b*d) + (a*d - b*c)*j

Notice that the imaginary part is equivalent to the determinant. Also, using complex values allows the points to be easily summed component-wise in the other operations.

R + sp (46 bytes)
Assumes sp package is installed (https://cran.r-project.org/web/packages/sp/)
Takes a list of vertices, (for example list(c(0.,0.), c(1.,0.), c(1.,1.), c(0.,1.)))
Takes advantage of the fact that the "labpt" of a Polygon is the centroid.
function(l)sp::Polygon(do.call(rbind,l))@labpt

Actually, 45 40 39 bytes
This uses an algorithm similar to miles' Jelly answer. There is a shorter way to calculate determinants using a dot product, but there's currently a bug with Actually's dot product where it won't work with lists  of floats. Golfing suggestions welcome. Try it online!
;\Z♂#;`i¥`M@`i│N@F*)F@N*-`M;Σ3*)♀*┬♂Σ♀/

Ungolfing
         Implicit input pts.
;\       Duplicate pts, rotate right.
Z        Zip rot_pts and pts together.
♂#       Convert the iterables inside the zip to lists
         (currently necessary due to a bug with duplicate)
;        Duplicate the zip.
`...`M   Get the sum each pair of points in the zip.
  i        Flatten the pair to the stack.
  ¥        Pairwise add the two coordinate vectors.
@        Swap with the other zip.
`...`M   Get the determinants of the zip.
  i│       Flatten to stack and duplicate entire stack.
           Stack: [a,b], [c,d], [a,b], [c,d]
  N@F*)    Push b*c and move it to BOS.
  F@N*     Push a*d.
  -        Get a*d-b*c.
;Σ3*)    Push 3 * sum(determinants) and move it to BOS.
♀*       Vector multiply the determinants and the sums.
┬        Transpose the coordinate pairs in the vector.
♂Σ       Sum the x's, then the y's.
♀/       Divide the x and y of this last coordinate pair by 3*sum(determinants).
         Implicit return.

A shorter, non-competitive version
This is another 24-byte version that uses complex numbers. It's non-competitive because it relies on bug fixes that postdate this challenge. Try it online!
;\│¥)Z`iá*╫@X`M;Σ3*)♀*Σ/

Ungolfing
         Implicit input a list of complex numbers, pts.
;\       Duplicate pts, rotate right.
│        Duplicate stack. Stack: rot_pts, pts, rot_pts, pts.
¥)       Pairwise sum the two lists of points together and rotate to BOS.
Z        Zip rot_pts and pts together.
`...`M   Map the following function over the zipped points to get our determinants.
  i        Flatten the list of [a+b*i, c+d*i].
  á        Push the complex conjugate of a+bi, i.e. a-b*i.
  *        Multiply a-b*i by c+d*i, getting (a*c+b*d)+(a*d-b*c)*i.
           Our determinant is the imaginary part of this result.
  ╫@X      Push Re(z), Im(z) to the stack, and immediately discard Re(z).
           This map returns a list of these determinants.
;        Duplicate list_determinants.
Σ3*)     Push 3 * sum(list_determinants) and rotate that to BOS.
♀*Σ      Pairwise multiply the sums of pairs of points and the determinants and sum.
/        Divide that sum by 3*sum(list_determinants).
         Implicit return.

Python 2, 153 bytes
Uses no complex numbers.
P=input()
A=x=y=0;n=len(P)
for i in range(n):m=-~i%n;a=P[i][0];b=P[i][1];c=P[m][0];d=P[m][1];t=a*d-b*c;A+=t;x+=t*(a+c);y+=t*(b+d)
k=1/(3*A);print x*k,y*k

Try it online
Ungolfed:
def centroid(P):
    A=x=y=0
    n=len(P)
    for i in range(n):
        m=-~i%n
        x0=P[i][0];y0=P[i][1]
        x1=P[m][0];y1=P[m][1]
        t = x0*y1 - y0*x1
        A += t/2.
        x += t * (x0 + x1)
        y += t * (y0 + y1)
    k = 1/(6*A)
    x *= k
    y *= k
    return x,y

C++14, 241 bytes
struct P{float x;float y;};
#define S(N,T)auto N(P){return 0;}auto N(P a,P b,auto...V){return(T)*(a.x*b.y-b.x*a.y)+N(b,V...);}
S(A,1)S(X,a.x+b.x)S(Y,a.y+b.y)auto f(auto q,auto...p){auto a=A(q,p...,q)*3;return P{X(q,p...,q)/a,Y(q,p...,q)/a};}

Output is the helper struct P,
Ungolfed:
 //helper struct
struct P{float x;float y;};

//Area, Cx and Cy are quite similar
#define S(N,T)\  //N is the function name, T is the term in the sum
auto N(P){return 0;} \   //end of recursion for only 1 element
auto N(P a,P b,auto...V){ \ //extract the first two elements
  return (T)*(a.x*b.y-b.x*a.y) //compute with a and b
         + N(b,V...); \        //recursion without first element
}

//instantiate the 3 formulas
S(A,1)
S(X,a.x+b.x)
S(Y,a.y+b.y)

auto f(auto q,auto...p){
  auto a=A(q,p...,q)*3; //q,p...,q appends the first element to the end
  return P{X(q,p...,q)/a,Y(q,p...,q)/a};
}

Usage:
f(P{0.,0.}, P{1.,0.}, P{1.,1.}, P{0.,1.})
f(P{-15.21,0.8}, P{10.1,-0.3}, P{-0.07,23.55})

Clojure, 177 156 143 bytes
Update: Instead of a callback I'm using [a b c d 1] as a function and the argument is just a list of indexes to this vector. 1 is used as a sentinel value when calculating A.
Update 2: Not precalculating A at let, using (rest(cycle %)) to get input vectors offset by one.
#(let[F(fn[I](apply +(map(fn[[a b][c d]](*(apply +(map[a b c d 1]I))(-(* a d)(* c b))))%(rest(cycle %)))))](for[i[[0 2][1 3]]](/(F i)(F[4])3)))

Original version:
#(let[F(fn[L](apply +(map(fn[[a b][c d]](*(L[a b c d])(-(* a d)(* c b))))%(conj(subvec % 1)(% 0)))))A(*(F(fn[& l]1))3)](map F[(fn[v](/(+(v 0)(v 2))A))(fn[v](/(+(v 1)(v 3))A))]))

At less golfed stage:
(def f (fn[v](let[F (fn[l](apply +(map
                                    (fn[[a b][c d]](*(l a b c d)(-(* a d)(* c b))))
                                    v
                                    (conj(subvec v 1)(v 0)))))
                  A (* (F(fn[& l] 1)) 3)]
                [(F (fn[a b c d](/(+ a c)A)))
                 (F (fn[a b c d](/(+ b d)A)))])))

Creates a helper function F which implements the summation with any callback l. For A the callback returns constantly 1 whereas X and Y coordinates have their own functions. (conj(subvec v 1)(v 0)) drops the first element and appends to the end, this way it is easy to keep track of x_i and x_(i+1). Maybe there is still some repetition to be eliminated, especially at the last (map F[....

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Ungolf batch programs
This question wants you to golf batch programms. In Batch you can use
set x=averylongbatchcommand
%x% arg1

which expands to
set x=averylongbatchcommand
averylongbatchcommand arg1

Your task is it to expand these statements.
As you can also use set  for arithmetic purposes like this:
set x = 0
set /a x= %x%+1

you should ignore the statements where the pattern with set /a is applied.
There will never be something like
set s=SET
%s% s=%s% a

where the variable is assigned using itself as command. But you have to handle things like
b:
set a =echo
%a% Hello World!
set a=goto
%a% b

Scoring
This is code-golf so the answer with the fewest bytes wins.
Testcases
set s=set
%s% e=echo
%e% I will have to use this exact thing very often because
%e% it absolutely wouldn't be shorter if i just left out these set statements

Expands to:
set s=set
set e=echo
echo I will have to use this exact thing very often because
echo it absolutely wouldn't be shorter if i just left out these set statements

set s=set
%s% i=0
set g=goto
:a
if %i%==15 (
%g% e
echo %i%
)
%s% /a i=%i%+1
%g% a
:e
%s% i=0
%g% a

Expands to:
set s=set
set i=0
set g=goto
:a
if %i%==15(
goto e
echo %i%
)
set /a i=%i%+1
goto a
e:
set i=0
goto a

set s=set
%s% s=%s% a=

Mustn't be supported.

set a=echo
%a% Hi
set a=type
%a% log.txt

Expands to:
set a=echo
echo Hi
set a=type
type log.txt

set x = 0
set /a x= %x%+1

Expands to:
set x = 0
set /a x= %x%+1

I meant you shouldn't expand statements with /a.

Whats is the valid character set for variable names ? Can variable names have more than 1 character ? What if there is more than one = on a set line ? What is the behaviour of whitespace before or after = ?  In particular does space after = become part of the assigned value ? Can the whitespace be tabs ? What is the behaviour of lines with an odd number of % ?

For this question you can assume that every variable name is 1 character from a-z case-insensitive. Also whitespaces before the first = are ignored. But everything after the first = including other = will be put in the variable.

Why doesn't i get set to 0 in the second testcase ?

@TonHospel I was confused by this as well, but the line before and after that example are meant to be read as one sentence, saying that references inside lines that start with set /a should not be substituted.

@MartinEnder Even so if %i%==15 should get substituted. Or does ignoring /a work backward ? And I'd like the op to clarify if it's OK to expand variables in set /a lines as long as no actual set is executed

@TonHospel %i% doesn't get replaced because it would require iterating the substutition (in the original input the line that will ultimately set i doesn't contain set yet).

@MartinEnder I Still don't understand. In the first testcase that is exactly how e gets set

@TonHospel Oh, I did not see that. In that case, I agree that the spec is still not clear. Putting on hold until this is resolved.