96
\$\begingroup\$

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!

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

129 Answers 129

1
2 3 4 5
70
\$\begingroup\$

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.

answered Oct 18, 2016 at 18:39
\$\endgroup\$
6
  • 15
    \$\begingroup\$ That ~- trick is cool, I will need to remember that. \$\endgroup\$ Commented Oct 18, 2016 at 19:25
  • \$\begingroup\$ how does the ~-trick work ? \$\endgroup\$ Commented Oct 19, 2016 at 14:08
  • 3
    \$\begingroup\$ @ShadowFlame - makes the number negative and ~ bit flips it. You can read a bit more about it on the tips page. \$\endgroup\$ Commented Oct 19, 2016 at 14:11
  • 2
    \$\begingroup\$ @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). \$\endgroup\$ Commented Oct 21, 2016 at 17:40
  • 5
    \$\begingroup\$ @MadPhysicist With Python, it works always, because ~ is defined as -x-1 \$\endgroup\$ Commented May 28, 2018 at 12:51
49
\$\begingroup\$

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.

Wheat Wizard
103k23 gold badges299 silver badges696 bronze badges
answered Oct 18, 2016 at 20:31
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 20, 2016 at 23:19
  • 6
    \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 21, 2016 at 5:59
33
\$\begingroup\$

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!

answered Oct 18, 2016 at 18:45
\$\endgroup\$
10
  • 1
    \$\begingroup\$ Nice trick with 1/s. \$\endgroup\$ Commented Oct 18, 2016 at 19:38
  • 1
    \$\begingroup\$ Super nice trick with ([c,...s]) you should write a tip \$\endgroup\$ Commented Oct 18, 2016 at 21:27
  • \$\begingroup\$ @edc65 Just for sake of clarity, this one was suggested by ETHproductions. \$\endgroup\$ Commented Oct 18, 2016 at 21:40
  • 1
    \$\begingroup\$ o well, someone has to write a tip anyway \$\endgroup\$ Commented Oct 18, 2016 at 21:42
  • 1
    \$\begingroup\$ @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) \$\endgroup\$ Commented Oct 19, 2016 at 7:16
29
\$\begingroup\$

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
]
Weird Glyphs
8952 silver badges26 bronze badges
answered Oct 18, 2016 at 19:45
\$\endgroup\$
6
  • 1
    \$\begingroup\$ There is usually a shorter way to get a constant than the obvious 2-factor multiplication. \$\endgroup\$ Commented Oct 18, 2016 at 20:16
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 18, 2016 at 20:58
  • \$\begingroup\$ you got one pair of brackets to much!? \$\endgroup\$ Commented Oct 21, 2016 at 14:04
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 21, 2016 at 22:34
  • \$\begingroup\$ Ah bugger, you're right. I didn't read carefully enough and made the last letter a function call like the others. \$\endgroup\$ Commented Oct 23, 2016 at 17:54
25
\$\begingroup\$

05AB1E, 11 bytes

S'(ý1g<')×ばつJ

Try it online!

Explanation:

S'(ý join input by "("
 1g< push length of input - 1, call it n
 ')×ばつ push a string with char ")" n times
 J concatenate
answered Oct 18, 2016 at 19:08
\$\endgroup\$
0
20
\$\begingroup\$

Jelly, (削除) 9 8 (削除ここまで) 7 bytes

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

L’Ø(xż@

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

How?

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

Original

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

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

j"(3")ṁṖ

TryItOnline

How?

j"(3")ṁṖ - 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
 3 - 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))))))))
answered Oct 18, 2016 at 18:43
\$\endgroup\$
3
  • 3
    \$\begingroup\$ Btw, ³ actually causes Jelly to print the current return value, so you never have two lists of chars. \$\endgroup\$ Commented Oct 18, 2016 at 21:09
  • \$\begingroup\$ Alternate 8 byter \$\endgroup\$ Commented Nov 2, 2021 at 12:36
  • \$\begingroup\$ @lyxal Nice. I don't think Ø( existed back then. \$\endgroup\$ Commented Nov 2, 2021 at 22:51
19
\$\begingroup\$

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.

answered Oct 18, 2016 at 19:02
\$\endgroup\$
1
  • \$\begingroup\$ +++++[->++++++++<],.,[>.>+<<.,]>+>[-<.>] is slightly shorter. \$\endgroup\$ Commented Oct 18, 2019 at 4:48
19
\$\begingroup\$

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

answered Oct 18, 2016 at 19:16
\$\endgroup\$
6
  • 3
    \$\begingroup\$ 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". \$\endgroup\$ Commented Oct 19, 2016 at 1:02
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 24, 2016 at 13:13
  • 1
    \$\begingroup\$ @Dada: that won't work, because it would put an additional () behind the last letter, e.g. f "abc" -> "a(b(c()))". \$\endgroup\$ Commented Oct 24, 2016 at 15:52
  • \$\begingroup\$ 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(\_->')'). \$\endgroup\$ Commented Oct 27, 2016 at 3:48
  • \$\begingroup\$ @JonPurdy: we don't have to handle empty input. intersperse requires import Data.List for another 17 bytes. \$\endgroup\$ Commented Oct 27, 2016 at 9:15
15
\$\begingroup\$

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.

answered Oct 18, 2016 at 18:40
\$\endgroup\$
2
  • \$\begingroup\$ Dangit. So fast... \$\endgroup\$ Commented Oct 18, 2016 at 18:43
  • \$\begingroup\$ @mbomb007 ...and far from optimal. ;) \$\endgroup\$ Commented Oct 18, 2016 at 19:05
15
\$\begingroup\$

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
answered Oct 18, 2016 at 19:21
\$\endgroup\$
14
\$\begingroup\$

><>, (削除) 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.

answered Oct 18, 2016 at 20:49
\$\endgroup\$
13
\$\begingroup\$

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
 )
;
answered Oct 19, 2016 at 1:24
\$\endgroup\$
1
  • \$\begingroup\$ the definition should run as declared and counted \$\endgroup\$ Commented Oct 22, 2016 at 11:25
11
\$\begingroup\$

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;}
answered Oct 18, 2016 at 19:21
\$\endgroup\$
4
  • \$\begingroup\$ 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) \$\endgroup\$ Commented Oct 19, 2016 at 7:58
  • \$\begingroup\$ @KevinCruijssen b+="("+a[l],++l)+")" gives you 144141148))),and BTW b+"("+a[l],++l)+")" is correct. and this was very silly mistake of mine(!=). \$\endgroup\$ Commented Oct 19, 2016 at 14:22
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 19, 2016 at 19:06
  • \$\begingroup\$ I post my version (82 bytes in Java 7) using only the input String as parameter. Verbose but not that bad ;) If you find something to change : codegolf.stackexchange.com/a/96745/59739 \$\endgroup\$ Commented Oct 20, 2016 at 14:10
10
\$\begingroup\$

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
 }
answered Oct 18, 2016 at 19:10
\$\endgroup\$
4
  • 6
    \$\begingroup\$ Where do you buy the keyboards for such a language!!! \$\endgroup\$ Commented Oct 19, 2016 at 13:13
  • \$\begingroup\$ @RonanDejhero Perhaps just remapping keys using cltr, shift, alt, capslock, numlock etc. \$\endgroup\$ Commented Oct 27, 2016 at 5:04
  • \$\begingroup\$ It can be shortened using trains, I guess: (∊'('∘,¨,')'⍴⍨⍴) But doesn't this add an extra couple of brackets? \$\endgroup\$ Commented Dec 24, 2019 at 12:02
  • \$\begingroup\$ Both solutions and also the one suggested by @Popov put an extra set of brackets around the output required in the question. \$\endgroup\$ Commented Nov 2, 2021 at 20:19
10
\$\begingroup\$

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.

answered Oct 18, 2016 at 20:42
\$\endgroup\$
1
  • \$\begingroup\$ 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! \$\endgroup\$ Commented Aug 28, 2018 at 13:29
9
\$\begingroup\$

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

answered Oct 18, 2016 at 18:42
\$\endgroup\$
9
\$\begingroup\$

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
answered Oct 18, 2016 at 19:39
\$\endgroup\$
9
\$\begingroup\$

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!

answered Oct 19, 2016 at 7:08
\$\endgroup\$
8
\$\begingroup\$

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
answered Oct 18, 2016 at 20:38
\$\endgroup\$
8
\$\begingroup\$

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
answered Oct 19, 2016 at 4:45
\$\endgroup\$
0
8
\$\begingroup\$

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,")");
answered Oct 18, 2016 at 19:17
\$\endgroup\$
3
  • 1
    \$\begingroup\$ 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) \$\endgroup\$ Commented Oct 18, 2016 at 20:00
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 19, 2016 at 13:15
  • 1
    \$\begingroup\$ @Titus nice alternative Thank You \$\endgroup\$ Commented Oct 19, 2016 at 14:08
8
\$\begingroup\$

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)

answered Oct 18, 2016 at 20:42
\$\endgroup\$
5
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Oct 19, 2016 at 4:59
  • \$\begingroup\$ @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) \$\endgroup\$ Commented Oct 19, 2016 at 5:23
  • \$\begingroup\$ perl -F -E '$"="(";say"@F".")"x$#F' \$\endgroup\$ Commented Oct 19, 2016 at 7:27
  • \$\begingroup\$ You can get your other idea working with something like s/.(?=.)/s%$'%($&)%/reg, but it of course doesn't support strings containing regex metacharacters \$\endgroup\$ Commented Oct 19, 2016 at 10:31
  • \$\begingroup\$ @TonHospel Thanks a lot for all of that! (About the second one, I added \Q to support regex metacharacters) :-) \$\endgroup\$ Commented Oct 19, 2016 at 15:11
8
\$\begingroup\$

GNU sed, (削除) 37 (削除ここまで) (削除) 35 (削除ここまで) 31 bytes (30 +1 for -r argument)

Pure linux sed solution

:;s/([^(])([^()].*)$/1円(2円)/;t
  1. Naming the subsitution :; then calling it recursively with t
  2. Making 2 regex groups:
    • First group is first char of two consecutive characters which are not parenthesis
    • Second group is the second consecutive character and the rest of the string until end of line
  3. Add parenthesis around the second group 1円 ( 2円 )

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

Online tester

answered Oct 19, 2016 at 22:20
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Using only 2 groups seems to be enough. Capture the 2nd and 3rd together. \$\endgroup\$ Commented Oct 19, 2016 at 23:06
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 20, 2016 at 8:04
  • 1
    \$\begingroup\$ Blank labels are a GNU sed feature/bug, so maybe the title should be GNU sed. \$\endgroup\$ Commented Oct 20, 2016 at 13:43
7
\$\begingroup\$

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.

answered Oct 18, 2016 at 19:52
\$\endgroup\$
2
  • \$\begingroup\$ You can use the <End> key in insert mode instead of leaving insert mode and doing A \$\endgroup\$ Commented Nov 30, 2016 at 1:09
  • \$\begingroup\$ @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.) \$\endgroup\$ Commented Nov 30, 2016 at 1:26
7
\$\begingroup\$

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.
answered Oct 19, 2016 at 10:11
\$\endgroup\$
6
\$\begingroup\$

05AB1E, (削除) 22 (削除ここまで) (削除) 21 (削除ここまで) (削除) 19 (削除ここまで) 18 bytes

¤Ug<©FN1è'(}X®')×ばつJ

Try it online!

Explanation:

¤Ug<©FN1è'(}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
 N1è #push the Nth char of A
 '( #push '('
 X #push X
 ®')×ばつ #push ')' repeated B times
 J #join together
 #implicit print
answered Oct 18, 2016 at 18:49
\$\endgroup\$
5
\$\begingroup\$

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

answered Nov 28, 2016 at 19:19
\$\endgroup\$
5
\$\begingroup\$

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.

answered Oct 18, 2019 at 22:35
\$\endgroup\$
5
\$\begingroup\$

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
answered Dec 24, 2019 at 22:58
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to the site! \$\endgroup\$ Commented Dec 25, 2019 at 0:24
  • \$\begingroup\$ thank you! @WheatWizard \$\endgroup\$ Commented Dec 25, 2019 at 1:23
  • 1
    \$\begingroup\$ You can remove the ¹ to save a byte. It will use the input implicitly again, since the stack is empty. :) \$\endgroup\$ Commented Jan 3, 2020 at 9:12
4
\$\begingroup\$

Convex, 10 bytes

_'(*,円(')*

Try it online!

answered Oct 18, 2016 at 19:50
\$\endgroup\$
1
2 3 4 5

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.