Live data from Hacker News

Display 100 Hello World Without Using Loops

ajibanda.com

1–10 of 42 posts

Re: Display 100 Hello World Without Using Loops

#2
Decent enough explanation of recursion.

Why not take it further and produce a more general solution?

In JavaScript I'd write something like this:

    function recurseBetween(start, end, callback) {
      // Create a recursive function
      // which checks the limits and calls the supplied callback
      var recursiveCallback = function(i) {
        // Call the original callback
        callback(i);
        // If we're at the end, stop
        if(i >= end) {
          return;
        } else {
          // Else increment and recurse
          recursiveCallback(++i);
        }
      };
      // Start recursing with the start value
      recursiveCallback(start);
    }
Now you can use recurseBetween almost exactly as you would a for loop:

    recurseBetween(1, 10, function(i) {
      console.log(i);
    });
You could even abstract the start and max arguments as callbacks, and you could supply a callback to perform the increment too so that you're not limited to integral addition.

Re: Display 100 Hello World Without Using Loops

#4
post #3

Python version: exec "print 'Hello world'\n" * 100

that reminds me why I don't like Python. Ad-hoc tools (many) instead of a few general concepts working well together.

Btw at interview time this solution would not be acceptable, because you are using still a built-in language construct for looping.

Re: Display 100 Hello World Without Using Loops

#7
post #3

Python version: exec "print 'Hello world'\n" * 100

I think a better Python version would be print '\n'.join(['Hello world'] * 100) No need for exec.

Or just

    print "Hello, World\n" * 100
No need for join either, and ends with a newline

Re: Display 100 Hello World Without Using Loops

#10
post #4
post #3

Python version: exec "print 'Hello world'\n" * 100

that reminds me why I don't like Python. Ad-hoc tools (many) instead of a few general concepts working well together. Btw at interview time this solution would not be acceptable, because you are using still a built-in language construct for looping.

> because you are using still a built-in language construct for looping.

That... makes no sense, the code is not looping anywhere.

And if you could somehow disqualify this bit, then recursion most definitely wouldn't qualify.

Post reply on HN