# Return 1 - Popularity Contest [closed]

Create a function/subroutine which returns 1. You can make it as elaborate as you like, as long as it returns 1.

The Rules

The entry with the most upvote wins - just like any popularity contest. Good luck!

• +1 four downvotes but 13 Answers?, if people are having fun with this question why so many downvotes? – jsedano Jul 30 '13 at 22:48
• 13 answers, but only two of them have garnered any votes. Perhaps this is our version of the emacs vs vi question -- one where everyone has an answer but none of them are particularly better than another. – breadbox Jul 31 '13 at 19:16
• @anakata, because four (make that six now) people think that this is the kind of question they think would have been better not posted. Some people are against popularity-contest on principle, and this is scraping the bottom of that category. – Peter Taylor Aug 1 '13 at 10:55
• This is one of those places where codegolf fits uneasily into the stackexchange format. Compare the Collatz Conjecture, which is also trending right now. The answers are all pretty mundane (no offense), because it's not a good problem for creative golfing — the naive approach is also the shortest. Whereas in this question, the popularity-contest allows all kinds of interesting answers to a very trivial task. Far more enjoyable to read — but stackexchange is supposed to avoid open-ended stuff like this. Thus the downvotes. – breadbox Aug 1 '13 at 17:13
• @breadbox Point taken - I will make my challenges more interesting from now :) – Doorknob Aug 6 '13 at 2:12

Golf Script

1


It took a long time to optimise this code to its most pure, and dare I say it - beautiful form. Such elegance of the language does not come without years of dedicated practice. The program that, without a Zero-Instruction-Set-Computer can literally never be compressed any further. My entire code golf career has been leading to this moment.

I am free. I am alive.

I see the code that underlies the universe.

• Can you write a program that only uses a single bit? – Kevin - Reinstate Monica Dec 19 '13 at 5:16
• @Kevin Only in Minecraft (I've done it before - made a 3x5 px screen and everything). – Timtech Jan 12 '14 at 17:20
• without a Zero-Instruction-Set-Computer can literally never be compressed any further. Our current computers can easily handle 0 instructions programs. All you need a language that has: "The empty program returns 1" in its specification – Cruncher Aug 11 '14 at 20:02

## C

Two examples, using obscure language features such as “strong return” (return!) and the “approaches” operator (-->):

int foo(void) {
return! 0;
}

int bar(void) {
int i=7;
while (i --> 0);
return-i;
}


# Brainfuck

+++++++
+++++++
+++
+++
+++
+++
+++
++++++++++
++++++++++.


Or if you are not fun at parties:

+++++++[->+++++++<]>.

• That looks more like a lowercase l than a 1. – Joe Z. Mar 18 '15 at 0:49

## APL

one ← {⍴⍴⍴⍵}


⍴ gives you the dimensions of a vector. The dimension of that is always one-dimensional, so the dimension of that is always one. Or:

"Rho, rho, rho of X
Always equals one,
Rho is dimension; rho rho, rank
APL is fun!"

(I didn't write that verse, it's Stallman's.)

• I have learned the Modern Major Generals Song, sung the Money song by Monty Python and Still Alive from Portal... and that is still the nerdiest song that has ever been stuck in my head. Good find marinus! A good verse Stallman! – lochok Aug 22 '13 at 9:28
• The same thing in J: # @: # @: # (Spaces are optional) – ɐɔıʇǝɥʇuʎs Aug 26 '14 at 7:37

## Java

public static int funWithOne() {
try {
try {
return funWithOne();
} finally {
return funWithOne();
}
} catch (Throwable _) {
return 1;
}
}


This will call itself 21024 times (this number may vary on different platforms) before finally returning 1. Don't hold your breath, though; it will easily take much longer than the age of the universe.

• "This will call itself 2^1024 times" Why? I think its a stack issue. Try to call yourself until you run out of stack, then do it again, and again? – user8777 Aug 9 '13 at 6:24
• @LegoStormtroopr there's some try finally stuff here that keeps the stack low, but still has a lot of calls – Cruncher Dec 18 '13 at 15:05
• @LegoStormtroopr See this. – arshajii Dec 19 '13 at 1:19

Fish

x sends the program counter in a random direction. # is a wall that the program counter "bounces" off. This will literally wander around aimlessly until it finds the "^" and then print 1 and finish.

xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxx###xxxxxxxxxxxxxx
xxxxxxxxxx#;#xxxxxxxxxxxxxx
xxxxxxxxxx#n#xxxxxxxxxxxxxx
xxxxxxxxxx#1#xxxxxxxxxxxxxx
xxxxxxxxxx#^#xxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx

• +1 for both tiring the interpreter and letting other ><> pee in their pants. Lol. – tomsmeding Dec 21 '13 at 12:16
• It's nice how this is easily translated into Befunge 98; simply change every x into a ?, every # into a r, n into . and ; into @. However, this ><> program looks better than the equivalent Befunge. Translation shown here: ideone.com/ZyuSKk – Justin Jan 15 '14 at 5:49
• Maybe I like this too much; here is another Befunge, but this one takes ~4 million operations to finish. I imagine that it can be directly translated into ><> by changing every ? into a x and every # into a ! (should work fine when left the same too) and (of course) . to n and @ to ;. ideone.com/gfApjT – Justin Jan 15 '14 at 6:11
• @Quincunx looks like it should take about 2^10 tries, with an expected number of operation per try at about 10. This gives me about 2000 operations. Am I missing something? – Cruncher Mar 7 '14 at 16:01
• @Quincunx Nevermind, it's 4^10. Got it. lol. FYI, I'm pretty sure that code can be minimized greatly and still do the same thing. – Cruncher Mar 7 '14 at 16:02

## Unix Shell (Bourne, POSIX, bash, ksh, csh, …)

expr 0


This prints 0 but returns 1, which may come as a surprise to programmers used to other languages. You can turn off the printed output and see the return code by running expr 0 >/dev/null; echo $?. • I've been bit by this before. You want to know if a process exists? $(pidof progname) < 1 – Mr. Llama Aug 2 '13 at 17:10

# Java

This is one of my favorite Java specific question.

public static int ret1() {
try {
return 0;
} finally {
return 1;
}
}

• I don't get it... – The Guy with The Hat Jan 14 '14 at 14:57
• Trying to return in a try block instantly fires finally which returns 1 before the other return statement can run. – PsHegger Jan 14 '14 at 17:31
• Ah, okay. Thanks! – The Guy with The Hat Jan 14 '14 at 19:29
• Returning in a finally block should throw a compile error. I can't think of any legitimate use case for doing it. – Cruncher Aug 11 '14 at 20:00
• In C# it does throw compile error, but in Java it is possible. Of course it doesn't mean it's useful, neither can I think of any legitimate use case – PsHegger Aug 11 '14 at 20:02

## JavaScript

function getOne() {
return -~![];
}


Explanation:

• first ![] evaluates to false.
• then ~false becomes -1 because false is first casted to 0, and ~0 == -1.
• finally, --1 evaluates to 1.

Alternate:

return +!([][~~{}])


Crazy alternate (each line is exactly 80 chars long):

this[693741..toString(36)]('acnuftiao nobcbdaterbaurn +abeba!!be'.replace(/b./g,
function(b){return '{}()'.split('')['aecd'.split('').indexOf(b.charAt(1))]})[''+
'replace'](new RegExp('a'+Array(5).join('(.)'),'g'),(a='$')+'4321'.split([]+[]). join(a)))  • -~{}+[] is another approach. {}+[] evaluates to 0. – tristin Dec 17 '13 at 22:15 ## JavaScript // we all know that OOP == good function OneManager() { // constants == good too this.values = { ERROR: -1, // value on error ONE: 1 // desired value } this.value = this.values.ERROR // set the value to ERROR this.setValue = function(num) { if (typeof num !== "number") throw new Error('cannot set value to non-number') if (!this.value) this.value = this.values.ERROR // oh noes else this.value = num } } // initialize the one OneManager.prototype.initializeOne = function() { this.setValue(this.values.ONE) // set the value to ONE return true // return true for success } // get the value OneManager.prototype.getValue = function() { if (this.value == this.values.ERROR) { // if the value is ERROR throw new Error('value not initialized') } else return this.value // return the value } function getOne() { var m = new OneManager() // make a OneManager var success = m.initializeOne() // initialize the value if (success) return m.getValue() // return the value else { // there was an error in the initialization var retVal = m.values.ERROR // we will return an error delete m // maybe it's corrupted return retVal // return an error } } alert(getOne())  • That's one robust piece of code you got here. – mveroone Jan 3 '14 at 13:59 • @Kwaio I lost it reading your comment – Newbrict Mar 24 '14 at 7:14 • OO == good or OO === good? – JoshWillik Mar 24 '14 at 18:41 • @JoshWillik: Yes. ;-) – Doorknob Mar 24 '14 at 18:43 ## Haskell & The Church of the ADT data One = One deriving (Eq, Ord, Bounded, Enum, Show, Read)  This defines the one true One. This One is both the type denoting Oneness, and the constructor One, which is itself the nullary function that returns the one true, and only one value of type One, which is, behold, One. Usage in the ghci REPL: λ: One -- One returns the one true One One λ: One == One -- One is equal to itself, as no others are True λ: One < One -- One is no less than itself False λ: minBound :: One -- One is the least One there is, yet it is all you need One λ: maxBound :: One -- One is as big as the universe of One, it is omnipotent One λ: [ One .. One ] -- One is the beginning, and ending, of all that is One [One] λ: show One -- The textual gospel of One "One" λ: read "One" :: One -- To read the word of One, is to become one with One One  The full Book of One is now on-line. Loading it gets you both testaments: Computation and Arithmetic. This enables you to explore more truths: λ: One + One -- One can only add to its magnificence One λ: negate One *** Exception: One cannot be negated, mortal fool! λ: One div One -- One is indivisible One λ: One mod One *** Exception: Nothing can modulate the power of One λ: toRational One -- Ye shall know One as both Numerator and Denominator 1 % 1 λ: toInteger One * 42 -- One multiplies all to wholeness 42 λ: toRational One / 2 -- Even divided, One is on top 1 % 2  # Groovy -""" int getRandomNumber() { return 4; //chosen by fair dice roll. //guaranteed to be random. } """.indexOf(4)  Doesn't contain 4 • I think i've seen this on xkcd. – mveroone Jan 3 '14 at 14:02 • Yes, that was the idea :) – Fels Jan 6 '14 at 8:31 ## Perl sub ret1 { print$->$= }  (Despite appearances, the function doesn't print anything.) I know Perl programmers like to say TMTOWTDI, but this is a task for which T really MTOWTDI. # PHP <?php function getOne() { return 0 + "one" == 0; }  Edit: If you prefer a longer one, here's an alternative (it doesn't print anything): <?php function getOne() { return print('the' + 'integer' + 'between' + 0 and 2); }  ## C float one(void) { const int n = 24; // magic number float x = 0.5f; float y = x; int i; for (i = 0; i < n; ++i) { x *= 0.5f; y += x; } return y; }  • How did you come up with this? – Saurabh Rana Dec 20 '13 at 19:23 • It's the geometric series 1/2 + 1/4 + 1/8 + ... = 1. – Casey Chu Dec 21 '13 at 2:44 • and it loops 24 times because float has 24 bits of precision – phuclv Jun 4 '14 at 5:09 # Rhetorical Java You didn't say it had to be an integer 1. float one_F(){ return FloatFactoryFactory.getInstance(FloatFactoryFactory. defaultInstanceDescriptionString).getFactory(Locale.getLocale ("en-US")).createBuilder().setString("1.0").getResult(); }  Source: http://bash.org/?946461 ## JavaScript (ECMAScript really) function one() { return Number.length; }  Time for some spec porn. Section 15.7.3 states that the length property of the Number constructor is 1 (and we know that a constructor is a function object as mentioned in 4.3.4), and that's because section 15.3.5.1 says: The value of the length property is an integer that indicates the “typical” number of arguments expected by the function. However, the language permits the function to be invoked with some other number of arguments. …and since the Number constructor's typical number of arguments is 1, the length of Number is 1. So one could say that the length of a number in Javascript is 1. ## Perl sub one{$a[@a{@a[%a=map{@$a[@a{$a++=>$a}]+++$#$a+$a=>$a}$a]++}+$a] }  Open wide and say aaaaa. The creative concept was to nest braces inside brackets inside braces... as deeply as possible, while still returning the desired result, and only using a "one" variable ($a, @a, %a, @$a and $#$a are of course all different variables). Although this does modify its environment significantly, it will always return 1 on subsequent calls. To get a grasp of what it's doing, you might consider running this code: use Data::Dump qw(dump); for (1..8) { one(); dump(@a); dump(%a); dump(@$a);
}


## Tcl

proc return1 {} {
catch {(5+2-3)/4}
}


Does not work as you might think.

(5+2-3)/4 is not a valid command, so it throws an error (return -code 1), catch returns this number.

## MATHEMATICA

In my opinion, the most elegant mathematical way to return 1 using Mathematica:

-Exp[I Pi]


The Euler Identity.

## Java

public class print {
public static char getNum() throws Exception{
String method = print.class.getSimpleName()+Splitter.class.getDeclaredMethods().length;
return (char)Splitter.class.getMethod(method).invoke(null);
}
}
class Splitter{
public static char print1(){
return P.getNum();
}
}
class P{
public static char getNum(){
return s.charAt(s.length()-P.class.getSimpleName().length());
}
public void doNothing(){}
}


Can be adjusted to return any other positive number n by adding the methods printX for X from 1 to n into Splitter. For example, modifying Splitter to

class Splitter{
public static char print1(){
return P.getNum();
}
public static char print2(){
return P.getNum();
}
}


Will return '2', without any other changes necessary. The added methods should, apart from the name, be an exact duplicate of print1. Uses reflection to get the number of methods in splitter, and call a function with that name. P.getNum, which is then called, reads the stack trace and parses out the last character in the calling method, and displays it.

Calling print.getNum() return the character '1'

Edit - modified to use no String/integer/etc literals.

C#

It should depend on hardware architecture:

return IntPtr.Size / (Environment.Is64BitOperatingSystem ? 8 : 4);


WOW!

## C#

Merging this (controversial) one with the neighboring (controversial) Collatz Conjecture:

public int CollatzOne()
{
var current = new BigInteger(new Random().Next(1, Int32.MaxValue));
var history = new[] { new BigInteger(-1), new BigInteger(-1), new BigInteger(-1) };
do
{
history[0] = history[1];
history[1] = history[2];
history[2] = current;
if (current.IsEven)
current /= 2;
else
current = current * 3 + 1;
} while (current != history[0]);
return (int)history.Min();
}


# Ruby

Abusing the RNG...

Random.new(56417).rand(10000)


Generates a "random" number between 0 and 10000, and because I picked the right seed it just so happens to be 1. ;)

Script I used to find the number:

irb(main):001:0> (1..100000).select{|x|Random.new(x).rand(10000) == 1}
=> [14033, 25845, 35101, 36955, 45334, 56417, 87438, 87460, 99178, 99451]


### Javascript 8 bytes

is this simple enough?

(+!~~{})

• Returns can only be used in a function. Just saying. – Mama Fun Roll Feb 6 '16 at 4:54
• @ӍѲꝆΛҐӍΛПҒЦꝆ fixed ;D – dhazelett Feb 8 '16 at 17:03

# R

A classic:

TRUE + 0


+ tries to coerce its argument to a common type: here, because of the order of precedence, it coerces to integers. The coercion of TRUE to an integer gives 1.

• Would +TRUE not work? – Griffin Jul 31 '13 at 16:13
• @Griffin +TRUE happens to give TRUE. – plannapus Aug 1 '13 at 6:41
• Also FALSE + 1, am I correct? – Timtech Jan 12 '14 at 17:27
• @Timtech yes you are. – plannapus Jan 13 '14 at 7:54

## Turing Machine

Single-state Turing machine with B as the blank symbol, computes 1 (= 0.111... in base 2):

q B 1 R q


(This follows Turing's convention of starting with a blank tape, and prefixing '0.' to the generated infinite sequence.)

# C

It even includes documentation on its parameters.

    int
return_1
(x)     int
x;{
/*x
can
be:
any
val
ue.
***/ return
!x?1:x /x;}

• But that's a 2! – Joe Z. Apr 2 '14 at 17:00
• So? It's fully documented! – Michael Hampton Apr 2 '14 at 17:32

## Python

one = lambda zero = 0o11: zero > 1 and all(one(zero-1) for l in '1111111111') and 1 or one and zero or one()


one() will call itself 111,111,111 times, each time returning 1, before returning a final value of 1.

You can also specify the number of digits. For example, one(3) will return 1 only 111 times.

I might add an explanation later, but I really don't have time at the moment.

## R

NA ^ 0


Any number to the power of 0 is 1.