85
votes
\$\begingroup\$

A question similar to this has been asked a couple of years ago, but this one is even trickier.

The challenge is simple. Write a program (in your language of choice) that repeatedly executes code without using any repetition structures such as while, for, do while, foreach or goto (So for all you nitpickers, you can't use a loop). However, recursion is not allowed, in the function calling itself sense (see definition below). That would make this challenge far too easy.

There is no restriction on what needs to be executed in the loop, but post an explanation with your answer so that others can understand exactly what is being implemented.

For those who may be hung up on definitions, the definition of a loop for this question is:

A programming language statement which allows code to be repeatedly executed.

And the definition of recursion for this question will be your standard recursive function definition:

A function that calls itself.

Winner will be the answer that has the most upvotes on July 16th at 10 AM eastern time. Good luck!

UPDATE:

To calm confusion that is still being expressed this may help:

Rules as stated above:

  • Don't use loops or goto
  • Functions cannot call themselves
  • Do whatever you want in the 'loop'

If you want to implement something and the rules don't explicitly disallow it, go ahead and do it. Many answers have already bent the rules.

\$\endgroup\$
  • 27
    \$\begingroup\$ For those who want an easy trick, i can't be bothered posting it :P Just make 2 functions, function A calls function B and function B calls function A while 1 of the functions performs something. Since the function doesn't call itself it should be valid based on the criteria ^.^ \$\endgroup\$ – Teun Pronk Jul 9 '14 at 14:34
  • 2
    \$\begingroup\$ "Changed to popularity contest for a focus on creativity" Changing the question is cheating! \$\endgroup\$ – CousinCocaine Jul 9 '14 at 15:12
  • 4
    \$\begingroup\$ The definition of "recursion" isn't very useful. It would be better to disallow recursive functions, which are functions that refer to themselves, directly or indirectly. \$\endgroup\$ – lrn Jul 10 '14 at 5:59
  • 3
    \$\begingroup\$ What is unclear is the "definitions" of loop constructor and recursion. Neither are very precise. Example: rep(f){f();f();} - this is a statement (a function declaration is a statement in some languages) that allows executing code repeatedly. Is it disallowed. You ask for code to implement a loop. If that code is syntactically a statement, you have just disallowed it. Another example: f(b) { b(); g(b); }; g(b) { f(b); }. I'd say f is a recursive function (by being mutually recursive with g). Is it disallowed? \$\endgroup\$ – lrn Jul 10 '14 at 6:08
  • 3
    \$\begingroup\$ @CailinP, what I'm "hung up on" is that questions on the site should be on topic for the site: that means having a clear, objective specification, which this question does not. \$\endgroup\$ – Peter Taylor Jul 11 '14 at 10:20

132 Answers 132

0
votes
\$\begingroup\$

Shell

Let's not forget about the classic, only works in a script file:

#!/bin/sh
echo do something here
exec $0

Another one that also works on the command line, employing a signal handler recursively calling itself by unusual means:

trap 'echo "do something here"; kill -s USR1 $$' USR1; kill -s USR1 $$

A script file moving it's content into a new temporary file, sourcing itself and removing old temporary file:

#!/bin/sh
# Only remove tempfile previously created by ourselves
[ "$tempfile" -a -f "$tempfile" ] && rm -f "$tempfile"

echo 'do something here'

export tempfile=$(tempfile) || exit 1
cat "$0" >"$tempfile" || exit 1
. "$tempfile"
\$\endgroup\$
0
votes
\$\begingroup\$

JavaScript (ES6)

Small and smart.

+(a = {x:0,valueOf: ()=>(a.x++,+a)})

This code can be written like this:

a = {
    x: 0,
    valueOf: function() { 
        a.x++;
        a.valueOf();
    }
}
a.valueOf();

+(obj) tries to cast obj to number. It starts with calling obj.valueOf... And in this case, calling obj.valueOf results in an infinite loop, throwing stack overflow error.

\$\endgroup\$
0
votes
\$\begingroup\$

Roblox Lua

More events.

local n=0
local m=Instance.new("Message",game.Workspace)

script.ChildAdded:connect(function(e)
    wait()
    local k
    k=e.AncestryChanged:connect(function()
        wait()
        k:disconnect()
        e.Parent=script
    end)
    m.Text="Hi! "..n
    n=n+1
    e.Parent=game.Workspace
end)
Instance.new("IntValue",script)

Creates an IntValue as a child of the current script and then uses events to endlessly move it back and forth between the script and the workspace while producing output via a Message instance.

\$\endgroup\$
0
votes
\$\begingroup\$

Java 8

Stream.iterate("Look @ me slurping ur cpu", i -> i).forEach(System.out::println);

Starts an infinite stream with a string, and each next element is the same as the previous: i -> i. The stream is consumed by printing each element to stdout.

\$\endgroup\$
0
votes
\$\begingroup\$

AutoIt

I golfed this (sue me :P). It just writes 0 to the console very, very slowly (and maxes out one CPU core along the way). Compile as a.exe.

Exit ConsoleWrite(0)+Run("a")

If you want to run this (and you probably shouldn't), use this to kill it:

While 1
    ProcessClose("a.exe")
Wend
\$\endgroup\$
  • \$\begingroup\$ This IS recursion... \$\endgroup\$ – Mega Man Jun 19 '16 at 9:22
0
votes
\$\begingroup\$

Standard C89, no extensions

#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    jmp_buf b;
    int i = 0, j;

    if (argc > 1) i = atoi(argv[1]);
    if (i<=0) i = 10;

    j = setjmp(b);

    if (j<i) {
        printf("%d\n", j);
        longjmp(b, j+1);
    }
    return EXIT_SUCCESS;
}

Compiles cleanly with gcc -std=c89 -g -Wall -Wextra -pedantic.

\$\endgroup\$
0
votes
\$\begingroup\$

C 42 bytes (w/single char return)

#include<stdio.h>
main(){printf("%9x",0);}

In this case, the printf is looping and printing up to 9 spaces to pad my hex output number 0. It is executing code (printing a space unless the output is filled) and looping (8 times in this case) without the usual loops. Tested on https://www.codechef.com/ide

\$\endgroup\$
0
votes
\$\begingroup\$

Molecule (v5.5+)

"lol!"~`q`n

Molecule has an built-in reflections system that allows code to be rewritten at runtime.

Output lol!, set the source code to the same one, which from v5.5 basically forces the interpreter to start reading from the start again.

\$\endgroup\$
0
votes
\$\begingroup\$

Python 2

class K(object):
    def __del__(self):
        print "You cannot stop the power of deallocators!"
        K()

This code goes into an infinite loop printing You cannot stop the power of deallocators.

Note that this does not work in Python 3

\$\endgroup\$
0
votes
\$\begingroup\$

Javascript ( 159 bytes )

This program relies on setInterval from javascript to iterate through an Enumerator (iterator). Uses a library I wrote to create an enumerator, and prints the value to the console

var e = _.Range(0,10).GetEnumerator();var id = setInterval(function(){var next = e.Next();if(next.Done){clearInterval(id);return;}console.log(next.Value);},1);

Image 1

\$\endgroup\$
-1
votes
\$\begingroup\$

VB6

Create a Timer on a form, set the Timer interval to 500

    Private Sub Timer1_Timer()
        Print "This is the lamest entry..."    
    End Sub

Although it will not show any more printing once the form is full, it will run until it is stopped.

\$\endgroup\$
  • \$\begingroup\$ Can you fix the formatting? I tried to but apparently it's less than the minimum edit by other people. Just put 4 spaces before each line of code. \$\endgroup\$ – Brendan Long Jul 11 '14 at 12:33
-2
votes
\$\begingroup\$

JavaScript

Array.foreach(function(item1, item2, ..){})

Array.prototype.foreach = function(callback) {

  var arr = this;
  var length = arr.length;
  var i = 0;
  var step = callback.length;
  
  function loopNext() {
    if (i < length) {
      loopBody();
    }
  }
  
  function loopBody() {
    callback.apply(arr, arr.slice(i,i+step));
    loopIncr();
  }
  
  function loopIncr() {
    i+=step;
    loopNext();
  }
  
  loopNext();
}


function testForeach() {
  var days = ['sun','Sunday',
              'mon','Monday',
              'tue','Tuesday',
              'wed','Wednesday',
              'thu','Thursday',
              'fri','Friday',
              'sat','Saturday'];

  var output = "";

  days.foreach(function(abbr, full) {
    output += full + '(' + abbr + '=' + this.indexOf(abbr) + ')\n';
  });

  document.getElementById('output').innerHTML = output;
}

testForeach();
<pre id="output"></pre>

\$\endgroup\$
  • \$\begingroup\$ Why the down votes? I followed the rules. The Array.forEach is functionality that I'm adding to JavaScript, not a built in function. It's like Tcl's foreach that can parameterize sets of values in a list. The array is flat but I'm iterating through it in a stride of 2 and naming the values abbr and full. \$\endgroup\$ – wolfhammer Sep 17 '15 at 10:24
  • \$\begingroup\$ x.foreach is an iterator, which is a loop, which is not allowed. \$\endgroup\$ – cat Jan 4 '16 at 15:03
  • \$\begingroup\$ @cat I created the foreach function without using loops or recursion in the function calling itself sense. \$\endgroup\$ – wolfhammer Jan 4 '16 at 19:29

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