17
\$\begingroup\$

You must produce a function which nests a string s inside an array, n times

>>> N("stackoverflow",2)
[['stackoverflow']]

Parameters:

  1. s - An ascii string
  2. n - An integer >= 0

Rules

  • Shortest code wins.
  • The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]

Inspired by: Nesting a string inside a list n times ie list of a list of a list

\$\endgroup\$
  • 6
    \$\begingroup\$ Does the output have to be a list, or can it be a string representing that list? \$\endgroup\$ – clismique Oct 17 '16 at 10:53
  • 2
    \$\begingroup\$ Can we take the parameters in any order? \$\endgroup\$ – Socratic Phoenix Oct 17 '16 at 10:56
  • \$\begingroup\$ @SocraticPhoenix I think unless explicitly forbidden, yes - you can take the input in any reasonable format (which would include taking the two as a list too I believe). Maybe someone more experienced can point to a relevant meta post. \$\endgroup\$ – Jonathan Allan Oct 17 '16 at 11:37
  • \$\begingroup\$ Will the string ever include an escaped "? E.g. N("stack\"overflow",5) \$\endgroup\$ – Riley Oct 17 '16 at 14:06
  • \$\begingroup\$ @Riley It could contain any ascii character \$\endgroup\$ – jamylak Oct 17 '16 at 23:48

54 Answers 54

1
2
1
\$\begingroup\$

Scala, 43 bytes

(s:Any,n:Int)=>((1 to n):\s)((_,x)=>Seq(x))

Explanation:

(s:Any,n:Int)=>   //define a function
  (               
    (1 to n)      //create a range with n elements
    :\s           //foldRight with s as a start value
  )(              //using the following function:
    (_,x)=>Seq(x) //ignore the value of the range and wrap the accumulator in a list
  )
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog), 6 bytes

(⊂⍣⎕)⎕

Try it online!

(note: the number of leading spaces in the output show how much the string is nested)

Explanation

⎕            take the string as input
  ⍣⎕         take the number (let's call it n) as input and n times
⊂             nest
             the string
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Might want to unhighlight your explanation \$\endgroup\$ – Zacharý Jun 25 '17 at 15:24
  • \$\begingroup\$ Save a byte: ⊂⍣⎕⊢⎕ \$\endgroup\$ – Adám Aug 21 '17 at 12:56
1
\$\begingroup\$

Clojure, 28 bytes

#(nth(iterate list %)%2) is the shortest (already posted) solution, so here is something different:

#(apply comp(repeat % list))

This takes arguments via currying:

(def f #(apply comp(repeat % list)))
((f 3) "test")
; ((("test")))
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Add++, 31 bytes

L,$Vd"]"*$"["*B]G$V"'"d@jGbU@jv

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Brachylog v2, 2 bytes

g₎

Try it online!

Although I can't think of what subscripting g could hypothetically do other than nesting arrays as it does, it can't be ruled out that getting stuck with a 10-byte solution on this challenge might have influenced it, so here's a version that doesn't use g at all:

Brachylog v2, 3 bytes

∈ⁱ⁾

Try it online!

The main difference between g and is that g constrains its output to be a single-element list containing its input, while constrains its output to be any list containing its input--it just so happens that in the absence of backtracking or any prior constraints the simplest list containing its input is the one containing nothing else. The difference which adds a byte is that subscripting g changes how many layers of array the output gets wrapped in, but it's far more useful in every circumstance except this one for to constrain the index of the input in the output when subscripted instead, so we need to use to iterate instead.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Haskell with extensions, 109 bytes

data Q a where E::Q();R::Q n->Q[n]
type family n&a where()&a=a;[n]&a=[n&a]
(#)::a->Q n->n&a
a#E=a
a#R n=[a#n]

Try it online!

Examples

"Hello"#E = "Hello"
"Hello"#R E = ["Hello"]
"Hello"#R(R E) = [["Hello"]]

Explanation

This is based loosely on the Agda solution. Since type literal numbers aren't very nice in Haskell, the numerical argument to (#) is given in unary format. Rather than taking space to define a Nat kind, we use () for zero and [] for successor. The type signature is mandatory thanks to the GADT argument.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Jellyfish, 8 bytes

p\Ai
 ;i

Try it online!

Unary ; wraps its argument in a list. Binary \ on a function and a value n iterates that function n times.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 2, 42 bytes

def f(a,b):
 if b:f([a],b-1)
 else:print a

Recursive function

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Did you see the shorter version of this that was posted by the OP? \$\endgroup\$ – Jonathan Allan Oct 17 '16 at 17:51
  • \$\begingroup\$ @Jonathan - yes I did after I had posted. Should I remove mine? \$\endgroup\$ – ElPedro Oct 17 '16 at 17:53
  • 1
    \$\begingroup\$ It's up to you. I'm not downvoting it. \$\endgroup\$ – Jonathan Allan Oct 17 '16 at 17:54
  • 1
    \$\begingroup\$ Thanks. Guess I'll leave it as an alternative until it gets downvoted. \$\endgroup\$ – ElPedro Oct 17 '16 at 17:55
0
\$\begingroup\$

Postscript, 24 bytes (11 bytes in binary encoding)

{{1 array astore}repeat}

Takes arguments on the stack, n at top-of-stack and s under it

The binary encoding is

{{1\x92\x09\x92\x0b}\x92\x83}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Groovy, 33 37 34 Bytes

Groovy's inject method is weird, but essentially is the fold method.

{a,n->(0..<n).inject(a){i,r->[i]}}

Edited to make it valid for n=0 using ternary.

Edited again with ..< to make the integer range an empty set when n=0 thanks to @manatwork.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Is the wrapping count correct? I'm afraid it adds and extra layer. Anyway, {a,n->(0..<n).inject(a){i,r->[i]}} seems enough: pastebin.com/GwpBQd1A \$\endgroup\$ – manatwork Oct 17 '16 at 19:08
  • \$\begingroup\$ @manatwork Ahhh... THAT IS AWESOME. I've never seen that notation for integer ranges! \$\endgroup\$ – Magic Octopus Urn Oct 17 '16 at 20:19
0
\$\begingroup\$

RProgN, 22 Bytes

►xX=x=1\_1:[s]xPX=}x

Explination

►xX=x=1\_1:[s]xPX=}x
►                   # Spaceless segment.
 xX=                # Assign 'x' to X
    x=              # Assign the string input to 'x'
      1\_1:       } # Push 1, flip it under the number input Then floor it, converting it from a string(?) to an integer, push another one, execute it as a for loop (i=1; i<=INPUT; i+=1)
           [            # Pop the incrementer of the for loop. We don't need it here.
            s]      # Push a new stack, then clone it.
              xP        # Push x, (Either the current bottom stack or the string), Push it to the new stack
                X=  # Assign it back to 'x' (This is why we set X to x)
                   x    # Push x to the reg stack. Implicitly return.

Easy enough, fun to finally get to use multi-dimensional stacks.

Try it Online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Lua, 47 Bytes

function(a,b)for _=1,a do b={b}end return b end

A huge amount of this is boiler plate, because of Lua. for _=1,a do b={b}end is the real meat.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Lithp, 48 Bytes

#S,N::((if (== 0 N) (S) ((list (n S (- N 1))))))

Can be assigned to a variable or function definition like so:

(def n #S,N::((if (== 0 N) (S) ((list (n S (- N 1)))))))

And called:

(print (inspect (n "stackoverflow" 5)))

[[[[["stackoverflow"]]]]]

(inspect is used because JS' print method stops if the object is too deep.)

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Convex, 4 bytes

'a*~

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

GNU sed 44 Bytes

Includes +1 for -r

s/(.*),(1*)/\2"\1"\2/
:;s/1(.*".*)1/[\1]/;t

Try it online!

Takes the depth to nest the string as a unary number based on this consensus
Example:

$ echo 'stack"o,verflow,1111' | sed -rf nest.sed
[[[["stack"o,verflow"]]]]
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Haskell, 41 bytes

Actually, it can be done with Haskell's standard list type. Here is how:

n?s|m<-([1..n]>>)=read$m"["++show s++m"]"

m is a local helper function that repeats a string n times. It is used in ? to prepend n [ and append n ] to the result of show s, which for a string s is that string surrounded by quotation marks and with its possible own quotation marks escaped. This is then parsed by read which tries to return the type at which the result is used. The infered type of ? is (Enum a2, Num a2, Read a, Show a1) => a2 -> a1 -> a. It could be specialized by setting a1 to String and a2 to Integer or Int, removing all but one of the constraints. But of course it is golfier to let the compiler infer a complicated type than to explicitely state a simple one.

Now simply calling the function in the interpreter gives an ambigous type variable error, but we can state the expected type or use the value in a way that gives enough information to infer the type:

Prelude> 2 ? "codegolf" :: [[String]]
[["codegolf"]]
Prelude> putStrLn $ 2 ? "hi" !! 0 !! 0
hi
Prelude> [[["test"]]] ++  (3 ? "hi")
[[["test"]],[["hi"]]]
Prelude> map(map("a":)) $  [2 ? "x" ++ 2 ? "y"] ++ 3 ? "z"
[[["a","x"],["a","y"]],[["a","z"]]]
Prelude> let x=(2 ? "golf") in (x,"code"++x!!0!!0)
([["golf"]],"codegolf")
Prelude> 0 ? "hi" ++ "!"
"hi!"

There is no reason to only use strings:

Prelude> map(map not) $ 2 ? False
[[True]]
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Julia 77 bytes

U(n)=Val{n}
g(::U(1),s)=[s]
g{n}(::U(n),s)=[g(U(n-1)(),s)]
f(n,s)=g(U(n)(),s
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Axiom, 60 43 bytes

f(a:Any,c:NNI):Any==(c<1=>a;f(copy[a],c-1))

Possibly one can use less characters but this is one here compile smoothly without warning... I don't know too if it is right copy one parameter in a recursive function but this silent all warning...

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Japt, 8 bytes

V´?[ß]:U

Try it online!

Requires the -Q flag in order to output the returned array with the brackets and quotes.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Symbolic Python, 31 bytes

__('_=_[_>_]'+';_=[_]'*_[_==_])

Try it online!

__('_=_[_>_]'                       Var1 = input string
             +'     '*_[_==_])      Nest depth times do:
               ;_=[_]                   Make Var1 a list containing itself
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Proton, 23 bytes

f=s=>n=>n?f([s])(n-1):s

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Tcl, 42 bytes

proc N s\ t {time {set s \{$s\}} $t;set s}

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Recursive approach did not render shorter: 50 bytes proc N s\ t {expr {$t?"\{[N s [expr $t-1]]\}":$s}} tio.run/##K0nO@f@/oCg/… \$\endgroup\$ – sergiol Nov 15 '17 at 17:42
0
\$\begingroup\$

Common Lisp, 43 bytes

(defun f(x n)(if(= n 0)x(list(f x(1- n)))))

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 3, 34 bytes

f=lambda s,n:n and f([s],~-n)or s

Try it online!

This might be about as short as I can make it.

Turns out, if you look at super old submissions, you can shave bytes off that you didn't see before. Huh.

| improve this answer | |
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.