Live data from Hacker News

Display 100 Hello World Without Using Loops

ajibanda.com

31–40 of 42 posts

Re: Display 100 Hello World Without Using Loops

#31
post #12
post #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; } e…

Here's a completely abstracted version, but I'm certain it's less clear to use ;) function recurseBetween(initial, hasEnded, modify, callback) { // Overwrite the callback with a recursive version: var recursiveCallback = function(i) { // Call the original callback callback(i); // If we're at the end, stop if(hasEnded(i)) { return; } else { // Else increment and recurse recursiveCallback(modify(i)); } }; // Start recu…

What you're inventing here is usually called "unfold". I don't know javascript, but here it is in close relative Scheme:

    (define (unfold p f g seed)
      (if (p seed)
        '()
        (cons (f seed) (unfold p f g (g seed)))))
And how you would call it to print "Hello world!" 100 times:

    (unfold (lambda (x) (> x 100))
            (lambda (x) (display "Hello world"))
            (lambda (x) (+ x 1))
            1)
'p' is your predicate. It determines when to stop unfolding. It takes the current value ('seed') and returns a boolean that's True when you're done. It's your 'hasEnded'.

'f' is what to do for each 'seed' value. In this case, it ignores the current value and just prints "Hello world". It's your 'callback'.

'g' maps each 'seed' value to the next 'seed' value. It's your 'modify'.

'seed' is the initial state for the unfold. It's your 'initial'.

-----

There are a couple other caveats to do with this being an expression rather than a statement, but it doesn't really matter right now. There are a million other cool things about unfolds (and folds, and other higher-order functions), but I'm not sure I could conscionably point you in the right direction since they lead to dangerous places.

Speaking of which, here is an unfold in Haskell, where it may (may) be clearer:

    unfold p f g seed  | p seed    = []
                       | otherwise = x:xs
                           where
                             x  = f seed
                             xs = unfold p f g (g seed)

    sequence_ $ unfold (>100) (const $ print "Hello world!") (+1) 1
I say 'an' unfold, because there are a whole bunch of cool ways to do it (and some of them look nothing like this).

Re: Display 100 Hello World Without Using Loops

#32
post #6
post #3

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

Why the exec? print "Hello world\n" * 100

That was the first thing that popped into my head upon reading the headline, though I abstracted it a bit:

  def print_many(n):
      print("hello, world\n" * n)
Though the `exec` option given above certainly is... interesting. :)

Re: Display 100 Hello World Without Using Loops

#33
post #12

Earlier quoted context omitted.

Here's a completely abstracted version, but I'm certain it's less clear to use ;) function recurseBetween(initial, hasEnded, modify, callback) { // Overwrite the callback with a recursive version: var recursiveCallback = function(i) { // Call the original callback callback(i); // If we're at the end, stop if(hasEnded(i)) { return; } else { // Else increment and recurse recursiveCallback(modify(i)); } }; // Start recu…

What you're inventing here is usually called "unfold". I don't know javascript, but here it is in close relative Scheme: (define (unfold p f g seed) (if (p seed) '() (cons (f seed) (unfold p f g (g seed))))) And how you would call it to print "Hello world!" 100 times: (unfold (lambda (x) (> x 100)) (lambda (x) (display "Hello world")) (lambda (x) (+ x 1)) 1) 'p' is your predicate. It determines when to stop unfolding…

Yeah I've done a bit of haskell at uni, it only struck me later how similar it is(/can be) to JS.

Re: Display 100 Hello World Without Using Loops

#34
post #22

Earlier quoted context omitted.

Huh? This is a specific case of the * operator, which is overloaded for type string to return a repetition of the string. The only ad-hoc in the example is the print statement, which is gone in 3.2. How do you know the __mul__ operator overload for string is implemented with iteration?

> This is a specific case of the * operator, which is overloaded It is not operator overloading in the strictest sense, but more of duck typing. In Python (and Ruby), operators are syntactic sugar for method calls on the first operand. Operator overloading on the contrary suggests a function add(a, b) that reacts differently through polymorphism (i.e according to the types of its arguments). The distinction is import…

My hope in using the phrase "operator overloading" was to bring to mind the familiar concept of operator ad-hoc polymorphism (which I would maintain duck typing is an example of) rather than to misleadingly describe the internals of the Python language. Nonetheless you are quite right on the details.

Re: Display 100 Hello World Without Using Loops

#35
These are fun.

In C++, make the compiler do your recursion:

  #include 

  template 
  void pr(const std::string &msg)
  {
      std::cout (msg);
  }

  template 
  void pr(const std::string &msg)
  {
  }

  int main(int argc, char *argv[])
  {
      pr("Hello World");
      return 0;
  }

Re: Display 100 Hello World Without Using Loops

#36
Why don't you ask "What's the least efficient way to print a string 100 times?"

Unrolling loops can be a good thing when optimizing code, but you can't get much worse than tail recursion. It's always a win to eliminate this code pattern. The order of complexity is the same, but your stack will blow up for large N.

I don't know what you're looking for when posing this problem. A simple loop is already the most efficient technique.

loop good tail recursion bad

Of course, this is just a homework quiz, right?

Post reply on HN