title: Comparing two numbers

text:
# Question
Title: Comparing two numbers
## Challenge

Given two integers `A` and `B` as input, you must write a program which outputs if `A>B`, `A==B` or `A<B`.

The integers will be in any reasonable range supported by your language which includes at least 256 values.

Your program can be either a full program or a function, taking input via STDIN or function arguments.

## Outputs

If `A>B` output

```
A is greater than B

```

If `A==B` output

```
A is equal to B

```

If `A<B` output

```
A is less than B

```

Where you replace `A` and `B` for their integer values.

For example:

```
 A   B   Output
--  --   ------
 0   1   0 is less than 1
 5   2   5 is greater than 2
20  20   20 is equal to 20

```

## Winning

The shortest program in bytes wins.

## Leaderboard

```
var QUESTION_ID=55693,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# CJam, 47

```
q~_~-g"is
equal greater less
to than"N/Sf/f=*S*

```

Try it online

**Explanation:**

```
q~     read and evaluate the input (array of 2 numbers)
_      duplicate the array
~-     dump one array on the stack and subtract the numbers
g      get signum (-1 for <, 0 for ==, 1 for >)
"…"    push that string
N/     split into lines
Sf/    split each line by space
f=     get the corresponding word (for the signum) from each line
*      join the array of 2 numbers by the array of words
        it effectively inserts the words between the numbers
S*     join everything with spaces

```
> 11 votes

# Answer
# Python 2, ~~95~~ ~~94~~ 76 bytes

Input must be comma separated.

```
A,B=input();print A,'is',['equal to','greater than','less than'][cmp(A,B)],B

```
> 20 votes

# Answer
# Labyrinth, ~~180~~ ~~152~~ 149 bytes

```
<
?01.23.511.501.23};,!:?
:
= ;3.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
; ;8.101.115:..""""""""""""^
1
.113.117.97.108.32.116.111.32.{!@

```

**Edit:** Managed to shave off 3 bytes by reusing `10` between `101`, `103` and `108` (the character codes of `e`, `g` and `l`). The explanation below does not reflect this, but it's not a substantial change.

## Explanation

There isn't much we can do in the way of saving bytes for printing the strings, that's just going to be long linear sections. So the main challenge in golfing is to avoid large amounts of unnecessary whitespace. That means we want the linear parts to "radiate out" from the left-most column. We can also gain some more savings by reusing the code that prints `than B`. So let's look at the control flow here:

The program starts on a grid rotation command `<`. This shifts the current row cyclically to the left with the IP on it, so we get this:

```
                                                     <
?.23.511.501.23};,!:?
:
= ;103.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""^
0
1.113.117.97.108.32.116.111.32.{!@

```

Now the IP is on an isolated cell, so it executes the same command again and again while the `<` travels further to the left until...

```
                    <
?.23.511.501.23};,!:?
:
= ;103.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""^
0
1.113.117.97.108.32.116.111.32.{!@

```

At this point, the IP has somewhere to go and executes the first linear section (the second row) from right to left. What it does is read `A`, copy, print. Consume the delimiting character between the numbers, print `is` (and spaces). Then read `B`, copy it and subtract `A` from it at the `-`.

At this point we hit first "fork in the road". If the difference yielded `0`, the IP keeps moving straight ahead towards the bottom branch. That branch simply prints `equal to` and then `B`.

Otherwise, the IP takes a left towards the two no-ops `""`. Then there's another fork. If the difference was negative, the IP takes another left towards the long upper branch. That branch simply prints `greater than` and then `B`.

If the difference was positive, the IP takes a right onto the lower branch, which prints `less`. Now we want to reuse the `than` from the other branch. But at the same time we don't want to connect the two branches later on, because we'd need a whole bunch of unnecessary spaces. Instead we use a few no-ops to align the lower branch with where the `than` begins on the upper branch and then start manipulating the source again with `^`:

```
                    <
?.23.511.501.23};,!:?
:                            .
= ;103.114.101.97.116.101.114 32.116.104.97.110.32.{!@
-""                          ^
1 ;108.101.115:..""""""""""""
0                            2
1.113.117.97.108.32.116.111.3 .{!@

```

Again, this is isolates the IP, so `^` is executed again and we get

```
                    <
?.23.511.501.23};,!:?        .
:
= ;103.114.101.97.116.101.114^32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""2
0
1.113.117.97.108.32.116.111.3 .{!@

```

Now the IP can continue moving to the right and print `than` and `B` as required.
> 10 votes

# Answer
# JavaScript (ES6), 66 bytes

```
(a,b)=>a+` is ${a<b?"less than":a>b?"greater than":"equal to"} `+b

```

Defines an anonymous function. Test by adding `f=` before it, and call it like `alert(f(4, 5))`

No savings to be had from the repetitive "than", unfortunately.
> 8 votes

# Answer
# Java, ~~114~~ 113 Bytes or ~~74 72~~ 67 if we used lambda notation

Thanks to Kevin Cruijssen for currying based solution:

`a->b->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b`

Old pre lambda solution

```
public void c(int a,int b){System.out.print(a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b);}

```

as user h.j.k meantion in comment, if we used lambda we can do significantly down to 74 bytes.

```
(a,b)->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b;

```
> 8 votes

# Answer
# Julia, ~~69~~ 66 bytes

```
f(A,B)="$A is $(A>B?"greater than":A<B?"less than":"equal to") $B"

```

This uses string interpolation to embed `A`, `B`, and the ternary inside a single string.

Saved 3 bytes thanks to Glen O.
> 7 votes

# Answer
# R, 80 bytes

```
function(A,B)cat(A,"is",c("less than","equal to","greater than")[2+sign(A-B)],B)

```
> 7 votes

# Answer
# Pyth, 52 49 bytes

```
jdm@cd)._-FQcj"
is
equal greater less
to than
"Qb

```
> 7 votes

# Answer
# Perl, ~~64~~ 63 bytes

```
#!/usr/bin/perl -p
s/ /" is ".("equal to ",greaterx,lessx)[$`<=>$']/e;s/x/ than /

```

62 bytes + 1 byte for `-p`. Takes input from STDIN, with the two numbers separated by a single space:

```
$ echo 1 2 | ./cmp
1 is less than 2
$ echo 42 -17 | ./cmp
42 is greater than -17
$ echo 123456789 123456789 | ./cmp
123456789 is equal to 123456789

```

## How it works:

The `<=>` operator returns -1, 0, or 1 depending on whether the first operand is less than, equal to, or greater than the second. Conveniently, Perl allows negative subscripts with arrays and slices, where the last element is at position -1, the second-to-last element is at position -2, and so on.

In the code

```
("equal to ",greaterx,lessx)[$`<=>$']

```

we use the return value of `<=>` as the subscript in a list slice to get the corresponding string, where `$`` is the first number and `$'` is the second.

To avoid repeating `than`, `x` is used as a placeholder and replaced in a second substitution at the end.

---

# Alternative solution, 63 bytes

```
#!/usr/bin/perl -p
@a=(equal,greater,than,to,less);s/ / is @a[$i=$`<=>$',!$i+2] /

```

62 bytes + 1 byte for `-p`. Takes space-separated input from STDIN just like the first solution.

## How it works:

This solution also uses a slice, but takes advantage of the fact that unlike list slices, array slices can be interpolated into strings (and the RHS of substitutions). This lets us drop the `/e` modifier and the quotes in the substitution operator.

The real trick is in the slice subscript:

```
@a[$i=$`<=>$',!$i+2]

```

For the different values of `<=>`, this gives:

```
$i  !$i+2  $a[$i]  $a[!$i+2]
----------------------------
-1    2     less      than
 0    3     equal     to
 1    2     greater   than

```

When an array or array slice is interpolated into a string, the elements are automatically joined by `$"` (by default, a single space).
> 6 votes

# Answer
# Mouse, 79 bytes

```
?A:?B:A.!" is "A.B.<["less than"]A.B.>["greater than"]A.B.=["equal to"]" "B.!$

```

When strings are encountered they're immediately written to STDOUT rather than being put on the stack. The stack can contain only integers.

Ungolfed:

```
? A:                            ~ Read an integer A from STDIN
? B:                            ~ Read an integer B from STDIN
A. !                            ~ Write A to STDOUT
" is "
A. B. < [ "less than" ]         ~ If A < B
A. B. > [ "greater than" ]      ~ If A > B
A. B. = [ "equal to" ]          ~ If A == B
" "
B. !                            ~ Write B to STDOUT
$                               ~ End of program

```
> 5 votes

# Answer
# MATLAB, 105 bytes

```
x=input('');y=input('');t={'less than','greater than','equal to'};
sprintf('%i is %s %i',x,t{(x>=y)+(x==y)+1},y)

```

Added a line break before sprintf, to ease readability. It works both with and without this line break, so it's not included in the byte count. Must hit enter between the two input numbers.
> 4 votes

# Answer
# GolfScript, 61 bytes

```
\.@.@="equal to "{.@.@>"greater""less"if" than "+}if" is "\+@

```

Expects 2 integers on the stack. Try it online.

How it works:

* `\.@.@` \- A and B are already on the stack, and this code piece makes the stack look like this: `ABBA`. `\` swaps the two top items on the stack, `.` duplicates the top item, and `@` rotates the 3 top items (`1 2 3` -\> `2 3 1`).
* Then, three items are pushed to the stack: the `=` sign, `"equal to "`, and the block between `{}`. The `if` statement does this: if the first argument evaluates to true, it executes the first code block (the second argument), otherwise, the second code block (the third argument). So if A and B are equal, it will push "equal to " on the stack. If they are not equal, it will execute the code between the block. Note that `=` pops the two top items from the stack, so now the stack looks like `AB`.
* Inside the block, you first see `.@.@`. Before these commands, the stack looks like `AB`, and after, the stack looks like `BAAB`. The commands are similar as the ones mentioned above.
* Then, there's another `if` statement. This time, it checks whether A \> B, and if true, it pushes "greater" on the stack. Else, it pushes "less" on the stack. After pushing one of these two, it will push " than " on the stack and concatenate it with the previous pushed string. `>` also pops the two top items of the stack, so now the stack looks like `BA"string"`.
* The next three commands are: `" is "\+`. `" is "` pushes that string on the stack (stack looks like `BA"string"" is "`), `\` swaps the two top items (stack looks like `BA" is ""string"`), and `+` concatenates the two top items (stack looks like `BA" is string"`).
* The last command, `@`, rotates the three stack items, so the stack now looks like: `A" is string"B`. GolfScript automatically prints the stack values on STDOUT once the program terminates, so then you get the desired output.
> 4 votes

# Answer
# Bash, 76

```
a=(less\ than equal\ to greater\ than)
echo $1 is ${a[($1>$2)-($1<$2)+1]} $2

```
> 4 votes

# Answer
# Fortran, 129

Fortran *arithmetic if* is perfect for this challenge

Test: ideone

```
read(*,*)i,j
if(i-j)1,2,3
1 print*,i," is less than",j
stop
2 print*,j," is equal to",j
stop
3 print*,i," is greater than",j
end

```
> 4 votes

# Answer
# Fourier, ~~147~~ 74 bytes

***Non-competing because string printing is newer than this challenge***

```
I~AoI~B` is `<A{1}{`greater than`}A<B{1}{`less than`}A{B}{`equal to`}` `Bo

```

**Try it on FourIDE!**

Dunno why I didn't allow printing before... It makes the code readable and is great for golfing
> 3 votes

# Answer
# Bash, 94 86 bytes (saved eight bytes thanks to Digital Trauma)

```
p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2

```

Test (on Linux):

```
echo 'p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2' > cmp.sh
chmod +x cmp.sh
./cmp.sh 10 12
10 is less than 12

```

The use of `[ ]` after `p=greater` is to prevent `||` operator from being evaluated before `=` in the expression `...&&p=greater||(($1<$2))...` (the operator precedence!).

The alternative would be using brackets around `(($1>$2))&&p=greater` and `(($1<$2))&&p=less` , but brackets make inner scope for variables, so `p` would be left unaltered.
> 3 votes

# Answer
# Lua, 118 bytes

I don't see enough Lua answers here so...

```
function f(a,b)print(a>b and a.." is greater than "..b or a==b and a.." is equal to "..b or a.." is less than "..b)end

```

Ungolfed:

```
function f(a,b)
    print(a>b and a.." is greater than "..b or a==b and a.." is equal to "..b or a.." is less than "..b)
end

```
> 3 votes

# Answer
# IA-32 machine code + linux, 107 bytes

Hexdump of the code:

```
60 89 e5 89 d0 e8 51 00 00 00 4c c6 04 24 20 38
d1 74 20 68 74 68 61 6e 4c c6 04 24 20 72 0d 68
61 74 65 72 68 20 67 72 65 44 eb 11 68 6c 65 73
73 eb 0a 68 6c 20 74 6f 68 65 71 75 61 68 20 69
73 20 88 c8 e8 12 00 00 00 89 ea 29 e2 89 e1 31
db 43 8d 43 03 cd 80 89 ec 61 c3 5b d4 0a 4c 04
30 88 04 24 c1 e8 08 75 f3 ff e3

```

Because of hardware limitations, the code works with numbers in the range 0...255.

Source code (can be assembled with gcc):

```
    .globl print_it
    .text
    .align 16
print_it:
    pushal;
    mov %esp, %ebp; // save esp (stack pointer)
    mov %edx, %eax; // put second number in al
    call prepend;   // convert al to string

    dec %esp;       // write ...
    movb $' ', (%esp); // ... a space
    cmp %dl, %cl;   // compare the numbers
    je equal;       // if equal, goto there

    push $0x6e616874; // write "than"
    dec %esp;       // write ...
    movb $' ', (%esp); // ... a space
    jb less;        // if below, goto there

greater:
    push $0x72657461; // write "ater"
    push $0x65726720; // write " gre"
    inc %esp;         // remove a space
    jmp finish;     // bypass the code for "less than"

less:
    push $0x7373656c; // write "less"
    jmp finish;     // bypass the code for "equal"

equal:
    push $0x6f74206c; // write "l to"
    push $0x61757165; // write "equa"

finish:
    push $0x20736920; // write " is "

    mov %cl, %al;   // put first number in al
    call prepend;   // convert al to string

    mov %ebp, %edx; // calculate the length ...
    sub %esp, %edx; // ... of the output message
    mov %esp, %ecx; // address of the message
    xor %ebx, %ebx; // set ebx to ...
    inc %ebx;       // ... 1 (i.e. stdout)
    lea 3(%ebx), %eax; // set eax=4 (syscall "write")
    int $0x80;      // do the system call
    mov %ebp, %esp; // restore the stack pointer
    popal;          // restore other registers
    ret;            // return

prepend:            // writes al converted to string
    pop %ebx;       // remove return address from the stack
appendloop:
    aam;            // calculate a digit in al, rest in ah
    dec %esp;
    add $'0', %al;  // convert the digit to ASCII
    mov %al, (%esp);// write the digit
    shr $8, %eax;   // replace al by ah; check if zero
    jnz appendloop; // nonzero? repeat
    jmp *%ebx;      // return

```

---

This is some serious abuse of the stack! The code builds the output message on the stack, from the end to the beginning. To write 4 bytes, it uses a single `push` instruction. To write 1 byte, it uses two instructions:

```
dec %esp
mov %al, (%esp);

```

By luck, most of the fragments to write are 4 bytes. One of them ("gre" in "greater") is 3 bytes; it's handled by pushing 4 bytes and removing one afterwards:

```
inc %esp

```

---

The routine that writes numbers in decimal form uses the `aam` instruction to divide `ax` by `10` repeatedly. It's advantageous that it calculates the digits from right to left!

---

Since there are two numbers to write, the code uses a subroutine, which is called twice. However, because the subroutine writes the results on the stack, it uses a register to hold the return address.

---

C code that calls the machine code above:

```
include <stdio.h>

void print_it(int, int) __attribute__((fastcall));

int main()
{
    print_it(90, 102);
    puts("");
    print_it(78, 0);
    puts("");
    print_it(222, 222);
    puts("");
    return 0;
}

```

Output:

```
90 is less than 102
78 is greater than 0
222 is equal to 222

```
> 3 votes

# Answer
# ShortScript, 98 bytes

```
←Α
←Β
↑Γαis
↔α>β→γgreater thanβ
↔α<β→γless thanβ
↔α|β→γequal toβ

```
> 3 votes

# Answer
## C, 155 136 127 83 bytes

```
f(a,b){printf("%d is %s %d\n",a,a>b?"greater than":a<b?"less than":"equal to",b);}

```
> 2 votes

# Answer
# C# 6, ~~113~~ ~~103~~ ~~100~~ 95 bytes

```
void C(int a,int b){System.Console.Write($"{a} is {a-b:greater than;less than;equal to} {b}");}

```

Thanks to edc65 for saving 13 bytes and to cell001uk for saving 5 bytes using C# 6's interpolated strings!
> 2 votes

# Answer
# JavaScript, ~~151 104 100 95~~ 92 bytes

```
a+=prompt()
b+=prompt()
alert(a+" is "+(a>b?"greater than ":a<b?"lesser than ":"equal to ")+b)

```

I managed to shorten with help of edc65
> 2 votes

# Answer
# Haskell, 87 bytes

One byte shorter than Otomo's approach.

```
a?b=show a++" is "++["less than ","equal to ","greater than "]!!(1+signum(a-b))++show b

```
> 2 votes

# Answer
# Python 2, 78 bytes

I love how `cmp()` is really useful, but it was removed in Python 3.

Using an anonymous function:

```
lambda a,b:`a`+' is '+['equal to ','greater than ','less than '][cmp(a,b)]+`b`

```

Not using a function (79 bytes):

```
a,b=input();print a,'is %s'%['equal to','greater than','less than'][cmp(a,b)],b

```
> 2 votes

# Answer
# Rust, 271 bytes

```
use std::cmp::Ordering::*;fn main(){let v:Vec<String>=std::env::args().collect();let a:u8=v[1].parse().unwrap();let b:u8=v[2].parse().unwrap();print!("{} is ",a);print!("{}", match a.cmp(&b) {Less=>"less than",Equal=>"equal to",Greater=>"greater than"});print!(" {}",b);}

```

## Pretty printed version:

```
use std::cmp::Ordering::*;

fn main() {
    let v:Vec<String> = std::env::args().collect();
    let a:u8 = v[1].parse().unwrap();
    let b:u8 = v[2].parse().unwrap();
    print!("{} is ", a);
    print!("{}", match a.cmp(&b) {
        Less => "less than",
        Equal => "equal to",
        Greater => "greater than"
    });
    print!(" {}", b);
}

```
> 2 votes

# Answer
# Pyth, ~~57~~ ~~55~~ 53 bytes

```
AQjd[G"is"@c"equal to
greater than
less than"b._-GHH)

```

This basically does:

```
["less than", "greater than", "equal to"][sign_of(A-B)]

```

Saved 2 bytes thanks to @AlexA.'s suggestion of using `A` instead of `J` and `K` and another 2 bytes by replacing the whole addition mess with a simpler subtraction.

Live demo and test cases.

## 55-byte version

```
AQjd[G"is"@c"less than
greater than
equal to"b+gGHqGHH)

```

Live demo and test cases.

## 57-byte version:

```
jd[JhQ"is"@c"less than
greater than
equal to"b+gJKeQqJKK)

```

Live demo and test cases.
> 1 votes

# Answer
# rs, 105 bytes

```
(\d+) (\d+)/\1 is (_)^^(\1) (_)^^(\2) \2
 (_+) \1_+/ less than
 (_+) \1 / equal to
_+ _+/greater than

```

*The trailing and preceding whitespace is very important!*

Live demo and all test cases.
> 1 votes

# Answer
# O, 67 bytes

```
jJ" is ""greater than""less than""equal to"JjK-.e\1<+{@}d;;' K++++p

```

Live demo.
> 1 votes

# Answer
# SWI-Prolog, 94 bytes

```
a(A,B):-(((A>B,C=greater;A<B,C=less),D=than);C=equal,D=to),writef("%t is %t %t %t",[A,C,D,B]).

```
> 1 votes

# Answer
# Haskell, 97 ~~94~~ 88 bytes

```
a!b|a>b="greater than "|a<b="less than "|1<3="equal to "
a#b=show a++" is "++a!b++show b

```

*thanks to nimi*

**94 byte version:**

```
d a|a>0="greater than "|a<0="less than "|1<3="equal to "
c a b=show a++" is "++d(a-b)++show b

```

**97 byte version:**

```
d a b|a>b=" greater than "|a<b=" less than "|1<3=" equal to "
c a b=show a++" is"++d a b++show b

```

my first time golfing :) (tested with ghci, size determined with du and stat)
> 1 votes

# Answer
# Ruby 1.9+, ~~73~~ ~~71~~ ~~70~~ 68 bytes

```
->a,b{[a,b]*" is #{%w{equal\ to greater\ than less\ than}[a<=>b]} "}

```
> 1 votes

# Answer
# Swift, 105 92 byte

```
func c(a:Int, b:Int){println("A is",(a==b ?"equal to":(a<b ?"less":"greater")," than"),"B")}

```

even shorter with Swift 2.0 (103 90 byte)

```
func c(a:Int, b:Int){print("A is",(a==b ?"equal to":(a<b ?"less":"greater")," than"),"B")}

```
> 1 votes

# Answer
# Processing, 92 bytes

```
void c(int a,int b){print(a+" is "+(a>b?"greater than ":a<b?"lesser than ":"equal to ")+b);}

```
> 1 votes

# Answer
# PHP, ~~103~~ 100 bytes

103 byte version.

```
function c($a,$b){echo "A is ".($a==$b?"equal to":($a>$b?"greater than":($a<$b?"less than":"")))." B";}

```

100 byte version (thanks jrenk)

```
<?php function c($i,$u){echo$i.' is '.($i>$u?'greater than ':($i==$u?'equal to ':'less than ')).$u;}

```
> 1 votes

# Answer
# PHP, 88 bytes

---

**PHP function, 88 bytes:**

```
function a($a,$b){echo"$a is ",$a-$b?($a>$b?"greater":"less")." than":"equal to"," $b";}
function b($a,$b){echo"$a is ",$a-$b?$a>$b?"greater than":"less than":"equal to"," $b";}
function c($a,$b){echo"$a is ",$a-$b?($a>$b?"greater":"less")." than $b":"equal to $b";}

```

Note than `$a-$b` can be replaced by `$a^$b`.

---

**Full program, 89 bytes:**

```
<?=$a=$argv[1]," is ",$a-($b=$argv[2])?($a>$b?"greater":"less")." than $b":"equal to $b";

```

---

I used:
> 1 votes

# Answer
# JavaScript, 84 bytes

```
f=function(a,b){alert(a+' is '+(a-b?(a>b?'greater':'less')+' than ':'equal to ')+b)}

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 56 bytes<sup>SBCS</sup>

Anonymous infix lambda.

```
{∊⍺'is ','less than' 'equal to' 'greater than'[2+×⍺-⍵]⍵}

```

Try it online!

`{``}` "dfn"; left argument is  and right argument is :

the right argument to the right of
`'less than' 'equal to' 'greater than'[``]` this list of three strings indexed by:
`⍺-⍵` left argument minus right argument
`×` sign of that
`2+` add two to that

`⍺'is ',` prepend the left argument and the string "is "

**ϵ**nlist (flatten)
> 1 votes

# Answer
# 05AB1E, 30 bytes

```
.S“ž‰€„†ª€ëîØ€ë“#2ôè¹'€ˆ.À`²ðý

```

Try it online!
> 1 votes

# Answer
# Befunge-93, 82 bytes

```
<v"equal to "$_v#!\!`0:\0:-&,,,"is ".::&
 v "less than "_" naht retaerg"
@>:#,_$-.

```

Try it online!
> 1 votes

# Answer
# Thue, 181 bytes

```
1,1::=o,x
x1::=1x
x]::=]x
!x::=!o
11,]::=1o,]
[1,]::=!vo
vx::=>x
[,11::=[,1x
[,1]::=!<x
[,]::=!=
o::=~1
>::=~ is greater than
<::=~ is less than
=::=~ is equal to
*::=:::
::=
[*]

```

Try it online!

The TIO version contains a trailing newline, but that’s only needed in this specific implementation; the specification doesn’t specify that the trailing newline is needed and other interpreters (e.g.) don’t require it. Similarly, the newlines in the output don’t show up in the linked interpreter.

## IO Format

Input and output are in unary strings of 1s, and there is a comma (but no spaces) between A and B. e.g. For A = 2 and B = 3, input `11,111`.

## Explanation (not really)

Unfortunately, my own motivation to write an explanation is inversely proportional to the reader’s desire for one, so I won’t write a detailed explanation. However, this ungolfed version that’s just split into sections might help (I’ll use `#` to denote comments):

```
# General stuff
1,1::=o,x
x1::=1x
x]::=]x
!x::=!o

# Check for greater than-ness
11,]::=1o,]
[1,]::=!vo
vx::=>x

# Check for less than-ness
[,11::=[,1x
[,1]::=!<x

# Check for equality
[,]::=!=

# Output
o::=~1
>::=~ is greater than
<::=~ is less than
=::=~ is equal to

# Input
*::=:::
::=
[*]

```

Look at the `Input`, `Output`, and `General stuff` sections first before looking at the other sections.

Also, maybe use this interpreter to step through some examples.

Original answer:

# Thue, 48 bytes, non-competing due to output format

```
*::=:::
1_1::=_
1__::=~>
__1::=~<
___::=~=
::=
*

```

Try it online!

### IO format

The numbers are inputted in unary as strings of `1`s, with an underscore on either side and an underscore between them. For example, to compare 2 and 3, the input would be `_11_111_`.

If the input is `_A_B_` then the output is `>` if \\$A\>B\\$, `<` if \\$A\<B\\$, and `=` if \\$A=B\\$.

### Explanation

I will assume some familiarity with Thue, so go read the *Language description* section of the Esolang page.

```
*::=:::     Take input (see also the last two lines).
1_1::=_     (Continually) subtract 1 from both numbers while both are positive.
1__::=~>    If B becomes 0 but A remains positive, A > B.
__1::=~<    If A becomes 0 but B remains positive, A < B.
___::=~=    If both A and B become 0, A = B.
::=
*

```
> 1 votes

# Answer
# Quipu, 154 bytes

```
'g'l'e\/' 3&5&2&[]1&' 4&
'r'e'q/\'i[][][]/\[]/\[]
'e's'u  's4&9&/\1@/\  /\
'a's'a  ' []<<1@??
't' 'l  /\--8&??
'e't'   \/  >>
'r'h't
' 'a'o
't'n
'h
'a
'n

```

Attempt This Online!

### Explanation

Threads 0 through 2 store the strings `greater than`, `less than`, and `equal to`, respectively. Then:

* Thread 3 inputs a number, stores it, and also outputs it
* Thread 4 outputs  `is` , then inputs a number and stores it
* Thread 5 calculates the value of thread 3 minus the value of thread 4
* Thread 6 loads the value of thread 5 and:
    + jumps to thread 9 if it is less than 0
    + jumps to thread 8 if it is greater than 0
    + continues to thread 7 otherwise
* Thread 7 loads the value of thread 2, outputs it, and jumps to thread 10
* Thread 8 loads the value of thread 0, outputs it, and jumps to thread 10
* Thread 9 loads the value of thread 1, outputs it, and continues to thread 10
* Thread 10 outputs a space
* Thread 11 loads the value of thread 4 and outputs it
> 1 votes

# Answer
# Vyxal , 34 bytes

```
=[«ß‟₆nḭ«|<[`∨⅛`|`∆ḭ`]`λ⊍`]?^‛is?^

```

Try it Online!

```
=[«ß‟₆nḭ«|<[`∨⅛`|`∆ḭ`]`λ⊍`]?^‛is?^ # Takes 2 numbers as arguments
=[«ß‟₆nḭ«                  ]        # If equal, push the base compressed string "equal to"
         |                          # Otherwise...
          <[`∨⅛`     ]              # If less than, push the string "less"
                |`∆ḭ`               # Otherwise, push the string "greater"
                      `λ⊍`          # Push the string "than"
                           ?        # Push the first number (due to the input mode, this turns out to be the second input)
                            ^       # Reverse the stack so we can prepend stuff
                             ‛is    # Push the string "is"
                                ?   # Push the second number (first input)
                                 ^  # Reverse the stack again
                                    # Implicit output. ṡ joins the stack on spaces

```
> 1 votes

# Answer
# C++, 109 bytes

```
#include<cstdio>
int x(int a,int b){printf("%d is %s %d",a,a>b?"greater than":a<b?"less than":"equal to",b);}

```
> 0 votes

# Answer
# Common Lisp, 92 bytes

```
(lambda(a b)(format t"~A is ~[less than~;equal to~;greater than~] ~A"a(1+(signum(- a b)))b))

```

More readably:

```
(lambda(a b)
  (format t "~A is ~[less than~;equal to~;greater than~] ~A"
  a                   ; first ~A
  (1+(signum(- a b))) ; gives 0, 1 or 2 which selects a clause in ~[ ~]
  b                   ; second ~A
))

```
> 0 votes

# Answer
# Inform 7, 109 bytes

```
To(A - value)T(B - value):say "[A] is [if A is B]equal to [else if A > B]greater than [else]less than ";say B

```

This defines a phrase used as `1 T 2;`.
> 0 votes

# Answer
# JavaScript, 92 bytes

```
a=+prompt(),b=+prompt();alert(a+" is "+(a>b?"greater than ":a<b?"less than ":"equal to ")+b)

```
> 0 votes

# Answer
# PHP 7, 91 bytes

```
<?=$a=$argv[1],[~ß–ŒßšŽŠž“ß‹ß,~ß–Œß“šŒŒß‹—ž‘ß][($b=$argv[2])<=>$a]?:~ß–Œß˜šž‹šß‹—ž‘ß,$b;

```

### Usage:

Save as ANSI in `file.php` and run:

```
php -derror_reporting=~E_NOTICE file.php A B

```

Is suppressing notices via CLI flag considered cheating? If so, here is a version that works with full error reporting, (**93 Bytes**)

```
<?=$a=$argv[1],@[~ß–ŒßšŽŠž“ß‹ß,~ß–Œß“šŒŒß‹—ž‘ß][($b=$argv[2])<=>$a]?:" is greater than ",$b;

```

### Some Explanation

For the string constants, I used undefined constants and bitwise invert them with `~`. PHP replaces undefined constants with the name of the constant (`foo` =\> `"foo"`) and allows special characters in constant names. This way you can save a byte even for strings with whitespace. Example:  =\> `" "`)

The spaceship operator `<=>` returns 0 if the operands are equal, -1 if the left operand is less than the right operand and 1 if the left operand is greater than the left operand. I use this as array index, to get " is equal to " and " is less than ". For the non-existing array key `-1` the result is `null` and thanks to `?:` we get " is greater than " in this case.
> 0 votes

# Answer
# PowerShell, 98 85 Bytes

(Thanks to tomkandy for the huge assist on the `param` and reminding me that PowerShell likes inline subexpression parsing, so go ahead and use it)

```
param($a,$b);"$a is $(@("equal to","greater than","less than")[$a.CompareTo($b)]) $b"

```

Essentially the same, just trimmed down quite a bit.

---

(Original below)

Decently competitive, I was somewhat surprised. Again, the `$` character and taking input is the downfall.

```
$a=$args[0];$b=$args[1];"$a is "+@("equal to","greater than","less than")[$a.CompareTo(+$b)]+" $b"

```

<sub>(Creating a function of two arguments is one byte longer than taking command-line input of two arguments, thanks to the `}` at the end)</sub>

```
function r{param($a,$b);<doing_stuff>}
$a=$args[0];$b=$args[1];<doing_stuff>

```

### Expanded:

```
$a=$args[0]
$b=$args[1]
"$a is " + @("equal to","greater than","less than")[$a.CompareTo(+$b)] + " $b"

```

Similar in concept to some other languages present, this is utilizing a feature of `x.CompareTo(y)`, which returns -1 if `x<y`, 0 if `x=y`, and 1 if `x>y`. We take that result and pull out the appropriate value from a dynamic array we just created, leveraging the fact that `[-1]` stands for the last item in the array.

Do note the `+` inside the `CompareTo(+$b)` statement -- an explicit cast to an Integer. If we left that off, it would try to utilize the String comparison instead, which yields odd behavior.
> 0 votes

# Answer
## Swift 2.0, 87 bytes

```
func g(a:Int,b:Int){print("A is",a==b ?"equal to":a<b ?"less than":"greater than","B")}

```
> 0 votes

# Answer
# beeswax, 68 chars

Non-competing answer, as I finished creating beeswax in December 2015, long after the start of the challenge.

The natural number range of beeswax is 64 bit unsigned integers, so this should be a valid solution. I’ll post a solution for 64 bit signed integers soon.

```
_T~T~{` is `Kp`equal to `{
p`ht ssel`#L~EL#~`greater than `{
>`an `{

```

You can clone the full and latest version of my beeswax interpreter, including examples and language specification from my GitHub repo.
> 0 votes

# Answer
# Julia, ~~90~~ 79 chars

Arrays in Julia use 1-based indexing, so adding 2 to the `cmp` function is necessary for proper access to the array.

```
c(a,b)=print(a," is ",["less than ","equal to ","greater than "][cmp(a,b)+2],b)

```

Result:

```
julia> c(2,2)
2 is equal to 2
julia> c(1654654,0)
1654654 is greater than 0
julia> c(-99999999999,-654654654)
-99999999999 is less than -654654654

```
> 0 votes

# Answer
# Mouse-2002, 73 bytes

Uses variables (lame, I know).

```
?a:?b:"A is "a.b.>["greater than"]a.b.<["less than"]a.b.=["equal to"]" B"

```

Explained:

```
? a: ? b:  ~ store input in a , b
"A is "               ~ print
a. b. > [           ~ testif
  "greater than"      ~ print
]
a. b. < [           ~ rinse && repeat
  "less than"
]
a. b. = [
  "equal to"
]
" B"
```

---

## Pure stack version: ~~96~~ 95 bytes

I had fun writing this one. It would be a LOT shorter if Mouse had a `2dup` instruction, but I implemented it myself instead.

```
??#D;#D;"A is ">["greater than"]<["less than"]=["equal to"]" B"
$D&swap &dup &rot &rot &over @

```

How this works:

```
? ? #D; #D; ~ get some input, then 2dup twice
"A is "                ~ print this
> [                  ~ test if gtr
  "greater than"       ~ print this
]                      ~ fallthrough
< [                  ~ repeat for next two conditions
  "less than"
]
= [
  "equal to"
]
" B"

$D       ~ def D():
 &swap        ~ ( x y -- y x )
 &dup         ~        ( y x -- y x x )
 &rot         ~               ( y x x -- x x y )
 &rot         ~                        ( x x y -- x y x )
 &over        ~                                 ( x y x -- x y x y )
@

```

We need the `2dup` instruction because comparison pops. Stack operations FTW!

Edit: for the same stack effect but a byte less, the second `swap` in the `2dup` implementation was changed to `rot`.
> 0 votes

# Answer
# Perl 6, 74 bytes

```
->\a,\b{say a~" is {<less equal greater>[1+(a <=>b)],<than to>[a==b]} "~b} # 74

```

Usage:

```
# give it a lexical name for ease of use
my &compare = ->\a,\b{ … }

compare 1,2;
compare 2,2;
compare 3,2;

say '';

compare "{ 2²⁵⁶ }\n", "\n{ 2²⁵⁶ + 1 }"

```

```
1 is less than 2
2 is equal to 2
3 is greater than 2

115792089237316195423570985008687907853269984665640564039457584007913129639936
 is less than
115792089237316195423570985008687907853269984665640564039457584007913129639937

```
> 0 votes

# Answer
# Python 3, 78 bytes

Translation of TheNumberOne's, using a double conditional instead of `cmp`, doesn't do too badly imo.

```
lambda a,b:print(a,'is',[['equal to','greater than'][a>b],'less than'][a<b],b)

```

You can also replace `cmp(a,b)` with `(a>b)-(a<b)`, but when I replaced it directly I found it one byte longer than my solution above. I also tried returning a string, instead of printing, but that was longer too.
> 0 votes

# Answer
# 05AB1E, ~~38~~ 36 bytes

```
²¹.S>ð“îØ€ë
ž‰€„
†ª€ë“«¶¡è¹… is«sð²J

```

I'm surprised there isn't already a 05AB1E answer. You can write almost any word in 05AB1E with just 2 bytes.

Try it online!
> 0 votes

# Answer
# SmileBASIC, 84 bytes

```
INPUT A,B
S=B-A?A;" is ";MID$("greater equal toless ",SGN(S)*8+8,8);"than"*!!S;" ";B

```
> 0 votes

# Answer
# Noether, ~~91~~ 79 bytes

```
I~aP" is "PI~b{ab=}{"equal to"P}{ab>}{"greater than"P}{ab<}{"less than"P}" "PbP

```

**Try it here!**

Note that while Noether is based heavily on Fourier, I have sacrificed golfability for functionality.
> 0 votes

# Answer
# PowerShell, 71 Bytes

```
param($a,$b)"$a is $($a-$b|% T*g "greater than;less than;equal to") $b"

```

an update to the existing powershell answer from 2 years ago.
> 0 votes

# Answer
# , 64 bytes

```
9;:inv@A.;&":,'is'~.@;cut@'equal to greater than less'{~1 2*>-<

```

Try it online!

`equal to` is joined by a non-break space.

`1 2*>-<`: –1, –2 if less; 0, 0 if equal; 1, 2 if greater than
`;&":,'is'~.@;` prepend `is`, then prepend A and B. Because 0, 0 yields `equal to,equal to`, there’s a `~.` to remove duplicates.
`9 A.` to shuffle B to the last position.
`;:inv@` join by spaces
> 0 votes

# Answer
# Swift \>=2.2, 85 bytes

```
func f(a:Int,b:Int){print(a,"is",a==b ?"equal to":(a>b ?"greater":"less")+" than",b)}

```

SwiftFiddle link

The two current Swift answers, both in Swift 2.0, are invalid because they print the literal letters "A" and "B" instead of the values given into the function. Other than that, this is pretty much identical to those two.

I can't find any Swift 2.0 or 2.1 compilers online, so I can't say for certain it works in those versions, but I don't see why it wouldn't. The function is `f(_:b:)` in Swift 2.2 and `f(a:b:)` in Swift \>=3.0.
> 0 votes

# Answer
# Thunno 2 , 30 bytes

```
ṛ‘~µ to%ɱṚ ċç%ƁÞ ċç‘'%/i¹s`is$

```

Attempt This Online!

Only works in \\$\le 2.2.0\\$. ATO is currently on v\\$2.1.9\\$.

To make this work in all versions use  instead of .

#### Explanation

```
ṛ‘...‘'%/i¹s`is$  '# Implicit input
ṛ                  # Compare the two inputs. Push -1 if a>b, 0 if a==b, 1 if a<b.
 ‘...‘             # Push compressed string "equal to%less than%greater than"
      '%/         '# Split it on "%"s to get ["equal to","less than","greater than"]
         i         # Index the number from before into this list
          ¹s       # Push the second input and swap
            `is    # Push the string "is"
               $   # And push the first input
                   # Implicit output of the stack joined by spaces

```
> 0 votes

---
Tags: code-golf, number
---


title: Nest a string inside an array n times

text:
# Question
Title: Nest a string inside an array n times
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

# Answer
> 11 votes
# Jelly, 2 bytes

Slightly confusing, since: (1) Jelly has no strings, only lists of characters; and (2); the output wont show the nesting. To see that this actually is doing what is asked look at a Python string representation of the result with:

```
W¡ŒṘ

```

An extra pair of `[]` will be present since the string itself will be a list of characters. For example

### How?

```
W¡ - Main link: s, n
W  - wrap left, initially s, in a list
 ¡ - repeat previous link n times

```

The proof-of-concept code adds:

```
W¡ŒṘ - Main link: s, n
  ŒṘ - Python string representation

```

# Answer
> 17 votes
# Java and C#, 62 bytes

```
Object f(String s,int n){return n<1?s:new Object[]{f(s,n-1)};}

```

Should work without modification in both Java and C#.

# Answer
> 12 votes
# 05AB1E, 3 bytes

**Code**

```
`F)

```

**Explanation**

```
`   # Flatten the input array on the stack.
 F  # Element_2 times do:
  ) # Wrap the total stack into a single array.

```

This means that this also works for the **0**-testcase, since the string is already on the stack.

Try it online!

# Answer
> 9 votes
## JavaScript (ES6), 20 bytes

```
d=>g=n=>n--?[g(n)]:d

```

Although people normally nag me to curry my functions for the 1-byte saving, this is a case where it actually contributes to the solution.

# Answer
> 7 votes
## Mathematica, 13 bytes

```
List~Nest~##&

```

# Answer
> 5 votes
# CJam, ~~7~~ 6 bytes

```
{{a}*}

```

Online interpreter

This is an unnamed function that takes its arguments from the stack as `S N`, `S` being the string and `N` being the wraps. You can execute it with the `~` operator, meaning eval.

Explanation:

```
{{a}*}
{      Open block    [A B]
 {     Open block    [A]
  a    Wrap in array [[A]]
   }   Close block   [A B λwrap]
    *  Repeat        [A:wrap(*B)]
     } Close block   ["S" N λ(λwrap)repeat]

```

# Answer
> 4 votes
# Javascript ES6, 23 bytes

Recursive function

```
f=(a,i)=>i?f([a],--i):a

console.log(f("stackoverflow",0))
console.log(f("stackoverflow",1))
console.log(f("stackoverflow",2))
console.log(f("stackoverflow",5))
```

Currying results in the same length

```
f=a=>i=>i?f([a])(--i):a

```

# Answer
> 4 votes
# Brachylog, 10 bytes

```
tT,?h:T:gi

```

Try it online!

### Explanation

```
tT,            T is the integer (second element of the Input)
   ?h:T:g      The list [String, T, built-in_group]
         i     Iterate: Apply built-in_group T times to String

```

This would be 3 bytes if it wasn't bugged. Here we need all this to get the list `[String, T, built-in_group]` even though `[String, T]` is already our input.

Unfortunately `:g` directly results in `[[String, T], built-in_group]`, which is not recognized properly by `i` because the integer `T` is inside the first list.

# Answer
> 4 votes
# MATL, 6 bytes

```
ji:"Xh

```

This produces a nested cell array as the output. With MATL's default display, however, you can't necessary *see* that's what it is since it won't show all of the curly braces. The demo below is a slightly modified version which shows the string representation of the output.

```
ji:"Xh]&D

```

**Try it Online**

**Explanation**

```
j       % Explicitly grab the first input as a string
i       % Explicitly grab the second input as an integer (n)
:"      % Create an array [1...n] and loop through it
    Xh  % Each time through the loop place the entire stack into a cell array
        % Implicit end of for loop and display

```

# Answer
> 4 votes
## Pyke, 3 bytes

```
V]1

```

Try it here!

# Answer
> 3 votes
# Python, 32 bytes

```
N=lambda s,n:n and[N(s,n-1)]or s

```

# Answer
> 3 votes
# PHP, 60 Bytes

```
for($r=$argv[1];$i++<$argv[2];)$r=[$r];echo json_encode($r);

```

48 Bytes if it looks only like the task

```
for($r=$argv[1];$i++<$argv[2];)$r="[$r]";echo$r;

```

# Answer
> 3 votes
# Pyth, 3 bytes

```
]Fw

```

Permalink

This will output something like `...[[[[['string']]]]]...`. It will not quote for zero depth: `string`.

Explanation:

```
]Fw
   Q Implicit: Eval first input line
]    Function: Wrap in array
  w  Input line
 F   Apply multiple times

```

If you want quoting on zero depth, use this 4-byte solution instead (explanation):

```
`]Fw
    Q Implicit: Eval first input line
 ]    Function: Wrap in array
   w  Input line
  F   Apply multiple times
`     Representation

```

# Answer
> 3 votes
# Ruby: 23 bytes

```
->n,s{n.times{s=[s]};s}

```

This is updated to make it a callable Proc rather than the original snippet. I'd be interested to know whether there's a way to have `s` implicitly returned rather than having to explicitly return it.

# Answer
> 3 votes
## C, ~~44 bytes~~, 41 bytes

```
int*n(int*s,int a){return a?n(&s,a-1):s;}

```

You can test it by doing the following:

```
int main(void) {
    char* s = "stackoverflow";

    /* Test Case 0 */
    int* a = n(s,0);
    printf("'%s'\n", a);

    /* Test Case 1 */
    int* b = n(s,1);
    printf("['%s']\n", *b);

    /* Test Case 2 */
    int** c = n(s,2);
    printf("[['%s']]\n", **c);

    /* Test Case 3 */
    int*** d = n(s,3);
    printf("[[['%s']]]\n", ***d);

    /* Test Case 4 */
    int********** e = n(s,10);
    printf("[[[[[[[[[['%s']]]]]]]]]]\n", **********e);

    return 0;
}

```

The output:

```
'stackoverflow'
['stackoverflow']
[['stackoverflow']]
[[['stackoverflow']]]
[[[[[[[[[['stackoverflow']]]]]]]]]]

```

Of course, you'll get warnings. This works on `gcc` on bash on my Windows machine (`gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)`, as well as on a true Linux machine (`gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)`).

# Answer
> 3 votes
# k, 3 bytes

```
,:/

```

Taken as a dyadic function, `/` will iteratively apply the left-hand function `,:` (`enlist`) n times to the second argument.

Example:

```
k),:/[3;"hello"]
,,,"hello"

```

# Answer
> 3 votes
# Thunno, \\$ 5 \log\_{256}(96) \approx \\$ 4.12 bytes

```
s{KZO

```

Attempt This Online!

If the inputs could be taken in any order, the leading `s` could be dropped.

#### Explanation

```
s{KZO  # Implicit input
s      # Swap so the number is on top
 {K    # Loop input number of times:
   ZO  # Wrap in a list
       # Implicit output

```

# Answer
> 2 votes
# Ruby, 25 characters

Rewrite of jamylak's Python solution.

```
f=->s,n{n>0?[f[s,n-1]]:s}

```

Sample run:

```
irb(main):001:0> f=->s,n{n>0?[f[s,n-1]]:s}
=> #<Proc:0x00000002006e80@(irb):1 (lambda)>

irb(main):002:0> f["stackoverflow",0]
=> "stackoverflow"

irb(main):003:0> f["stackoverflow",1]
=> ["stackoverflow"]

irb(main):004:0> f["stackoverflow",5]
=> [[[[["stackoverflow"]]]]]

```

# Answer
> 2 votes
## C# 6, 50 bytes

```
dynamic a(dynamic s,int n)=>n<2?s:a(new[]{s},n-1);

```

# Answer
> 2 votes
# Ruby, 24 bytes

```
f=->*s,n{s[n]||f[s,n-1]}

```

Called the same as in manatwork's answer, but a weirder implementation. `*s` wraps the input (a possibly-nested string) in an array. Then if `n` is zero, `s[n]` returns the first element of `s`, turning the function into a no-op. Otherwise, it returns `nil` since `s` will only ever have one element, so we pass through to the recursive call.

# Answer
> 2 votes
# , 6 bytes

```
Àñys$]

```

Try it online!

Explanation:

```
À      "Arg1 times
 ñ     "repeat:
  ys$  "surround this line
     ] "with square brackets

```

# Answer
> 2 votes
# Perl 6, 23 bytes

```
{($^a,{[$_]}...*)[$^b]}

```

## Expanded:

```
{ # bare block lambda with two placeholder parameters ｢$a｣ and ｢$b｣
  (

    # generate Sequence

    $^a,       # declare first input
    { [ $_ ] } # lambda that adds one array layer
    ...        # do that until
    *          # Whatever

  )[ $^b ]     # index into the sequence
}

```

# Answer
> 2 votes
## Agda, 173 bytes

Since the return type of the function depends on the number given as argument, this is clearly a case where a dependently typed language should be used. Unfortunately, golfing isn't easy in a language where you have to import naturals and lists to use them. On the plus side, they use `suc` where I would have expected the verbose `succ`. So here is my code:

```
module l where
open import Data.List
open import Data.Nat
L : ℕ -> Set -> Set
L 0 a = a
L(suc n)a = List(L n a)
f : ∀ n{a}-> a -> L n a
f 0 x = x
f(suc n)x = [ f n x ]

```

(I hope I found all places where spaces can be omitted.) `L` is a type function that given a natural `n` and a type `a` returns the type of `n` times nested lists of `a`, so `L 3 Bool` would be the type of lists of lists of lists of `Bool` (if we had imported `Bool`). This allows us to express the type of our function as `(n : ℕ) -> {a : Set} -> a -> L n a`, where the curly braces make that argument implicit. The code uses a shorter way to write this type. The function can now be defined in an obvious way by pattern matching on the first argument.

Loading this file with an `.agda` extension into emacs allows to use `C-c C-n` (evaluate term to normal form), input for example `f 2 3` and get the correct answer in an awkward form: `(3 ∷ []) ∷ []`. Now of course if you want to do that with strings you have to import them...

# Answer
> 2 votes
# Japt, 8 bytes

```
@[X]}gNÅ

```

Try it

# Answer
> 1 votes
## R, 39 40 bytes

EDIT: Fixed the `n=0` issue thanks to @rturnbull.

Function that takes two inputs `s` (string) and `n` (nestedness) and outputs the nested list. Note that R-class `list` natively prints output differently than most other languages, however, is functionally similar to a key/value map (with possibly unnamed keys) or a list in python.

```
f=function(s,n)if(n)list(f(s,n-1))else s

```

**Example**

```
> f=function(s,n)if(n)list(f(s,n-1))else s
> f("hello",3)
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "hello"

> # to access the string nested 5 times in the "list-object" named "list" we can do the following
> list = f("nested string",5)
> list[[1]][[1]][[1]][[1]][[1]]
[1] "nested string"

```

# Answer
> 1 votes
## 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.

# Answer
> 1 votes
# PHP, 44 bytes

```
function n($s,$n){return$n?n([$s],--$n):$s;}

```

nothing sophisticated, just a recursive function

# Answer
> 1 votes
## Haskell, ~~40~~ 38 bytes

```
data L=N[Char]|C L
f 0=N
f n=C. f(n-1)

```

Haskell's strict type system prevents returning different types (Strings vs. List of Strings vs. List of List of Strings,...), so I have to define my own type that accommodates all those cases. The main function `f` recursively calls `n` times the constructor `C` for nesting and `N` for the base case.

Usage example (with `deriving (Show)` added to the new `data` type to be able to print it): `f 4 "codegolf"` -\> `C (C (C (C (N "codegolf"))))`.

Edit: @Christian Sievers saved 2 bytes by rewriting the function in a point-free style for the string argument. Thanks!

# Answer
> 1 votes
## Python 2, 32 bytes

```
lambda s,n:eval('['*n+`s`+']'*n)

```

Puts `n` open brackets before the string and `n` close brackets before it, then evals the result. If a string output is allowed, the `eval` can be removed.

# Answer
> 1 votes
## Racket 83 bytes

```
(for((c n))(set! s(apply string-append(if(= c 0)(list"[\'"s"\']")(list"["s"]")))))s

```

Ungolfed:

```
(define (f s n)
  (for ((c n))
    (set! s (apply string-append
                   (if (= c 0)
                       (list "[\'" s "\']")
                       (list "[" s "]"))
                   )))
  s)

```

Testing:

```
(f "test" 3)

```

Output:

```
"[[['test']]]"

```

# Answer
> 1 votes
# Actually, 4 bytes

Input is `string` then `n`. Golfing suggestions welcome. Try it online!

```
`k`n

```

**Ungolfing**

```
          Implicit input string, then n.
`...`n    Run the function n times.
  k         Wrap the stack in a list.
          Implicit return.

```

# Answer
> 1 votes
## tinylisp (repl), 34 bytes

```
(d F(q((S N)(i N(F(c S())(s N 1))S

```

Defines a function `F`. Technically, tinylisp doesn't have strings, but this code will work for any data type it's given.

Ungolfed (key to builtins: `d` = define, `q` = quote, `i` = if, `c` = cons, `s` = subtract):

```
(d nest
 (q
  ((item number)
   (i number
    (nest (c item ()) (s number 1))
    item))))

```

Example usage:

```
tl> (d F(q((S N)(i N(F(c S())(s N 1))S
F
tl> (F 2 3)
(((2)))
tl> (F () 1)
(())
tl> (F (q Hello!) 7)
(((((((Hello!)))))))
tl> (F c 3)
(((<builtin function tl_cons>)))

```

# Answer
> 1 votes
# Clojure, 24 bytes

```
#(nth(iterate list %)%2)

```

Clojure is somewhat competitive here. `iterate` creates a sequence of `x, (f x), (f (f x)) ...`, `nth` returns needed element.

See it online: https://ideone.com/2rQ166

# Answer
> 1 votes
# 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
  )

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# Japt, 8 bytes

```
V´?[ß]:U

```

Try it online!

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

# Answer
> 1 votes
## 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")))

```

# Answer
> 1 votes
# Common Lisp, 43 bytes

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

```

Try it online!

# Answer
> 1 votes
# Add++, 31 bytes

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

```

Try it online!

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# Factor, 20 bytes

```
[ [ 1array ] times ]

```

Try it online!

* `1array` Create an array with one element from an object.
* `times` Call a quotation a certain number of times.

# Answer
> 1 votes
# Vyxal, 3 bytes

```
$(w

```

Try it Online!

# Answer
> 1 votes
# Arturo, 27 bytes

```
$[s,n][do.times:n->s:@[s]s]

```

Try it

Recursion is 2 bytes longer:

```
f:$[s,n][(0=n)?->s->f@[s]n-1]

```

# Answer
> 1 votes
# JavaScript, 23 bytes

```
f=(s,c)=>c?[f(s,c-1)]:s

```

Try it:

```
f=(s,c)=>c?[f(s,c-1)]:s

console.log(JSON.stringify(f("stackoverflow",0))); // 'stackoverflow'
console.log(JSON.stringify(f("stackoverflow",1))); // ['stackoverflow']
console.log(JSON.stringify(f("stackoverflow",2))); // [['stackoverflow']]
console.log(JSON.stringify(f("stackoverflow",5))); // [[[[['stackoverflow']]]]]
```

# Answer
> 1 votes
# Thunno 2, 3 bytes

```
s{W

```

Attempt This Online!

If we could take input the other way round, the `s` could be dropped.

#### Explanation

```
s{W  # Implicit input
s    # Swap so the number is on top
 {   # And, this many times, repeat the following:
  W  #  Wrap TOS (initially string input) in a list
     # Implicit output

```

# Answer
> 0 votes
# 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"]]]]

```

# Answer
> 0 votes
# Python 2, 42 bytes

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

```

Recursive function

# Answer
> 0 votes
# 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}

```

# Answer
> 0 votes
## 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.

# Answer
> 0 votes
# 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!

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# 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.)

# Answer
> 0 votes
# Convex, 4 bytes

```
'a*~

```

Try it online!

# Answer
> 0 votes
## 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]]

```

# Answer
> 0 votes
## 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

```

# Answer
> 0 votes
# 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...

# Answer
> 0 votes
# Symbolic Python, 31 bytes

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

```

**Try it online!**

```
__('_=_[_>_]'                       Var1 = input string
             +'     '*_[_==_])      Nest depth times do:
               ;_=[_]                   Make Var1 a list containing itself

```

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# Proton, 23 bytes

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

```

Try it online!

# Answer
> 0 votes
# Tcl, 42 bytes

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

```

Try it online!

---
Tags: code-golf, string
---