# N(e(s(t))) a string

To "function nest" a string, you must:

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

H(ello)

• Then, repeat this same step for every substring. So we get:

H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

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

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

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

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

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

Input:
a
Output:
a

Input:
42
Output:
4(2)

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

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

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

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

# Keg, 221615 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

?!&("$$)_^)&* 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

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

# Burlesque, 16 bytes

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

Try it online!

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

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

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

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

# 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? Aug 9, 2020 at 16:48
• 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. Aug 10, 2020 at 7:04

# Python 3, 51

Just a simple recursive function.

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

Try it online!

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

# 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

# KamilaLisp v0.2, 32 (APL SBCS)

$(⌿.← \λ(x y)\⍫∊ "{?y}({?x})")∘⌽ Equivalent to$(foldl1 \lambda(x y)\str:format "{?y}({?x})")@reverse.

# ThunnoD, $$\ 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
ZH  # And remove the last character
# Implicit output

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

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

# 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. May 1, 2023 at 19:26
• @DLosc thanks, updated. May 1, 2023 at 19:59

# 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<B>}):S Should work May 3, 2023 at 18:33
• It might need an extra B extends""?B:clause, haven’t tested it May 3, 2023 at 18:47

# ForceLang, 132 bytes

def S set
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

# tcl, 66

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

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

# 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
:?!;        Exits if counter == 0
9sso    Outputs closing paren
1-  Decrement counter
:             : Duplicate counter twice (so that it isn't discarded by the '~'

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