Recursive Countdown

Actionscript:
  1. loop(20);
  2.  
  3. function loop(i:int):void {
  4.     if (i <0) return;
  5.       trace(i);
  6.       loop(i - 1);
  7. }
  8.  
  9. /* outputs:
  10. 20
  11. 19
  12. 18
  13. 17
  14. 16
  15. 15
  16. 14
  17. 13
  18. 12
  19. 11
  20. 10
  21. 9
  22. 8
  23. 7
  24. 6
  25. 5
  26. 4
  27. 3
  28. 2
  29. 1
  30. 0
  31. */

This snippet uses a recursive function to count down from some number. Recursion is pretty useless in actionscript, it will eventually cause an error... If you were to try to countdown from a higher number it would choke pretty fast...

Been writing haskell lately so I have recursion on the brain.

This entry was posted in functions, misc and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

7 Comments

  1. Posted January 1, 2010 at 4:09 pm | Permalink

    It might be a good idea to change:

    if (i == -1)

    to:

    if (i < 0)

    Otherwise loop(-2) will infinitely recurse.

  2. Posted January 1, 2010 at 4:12 pm | Permalink

    that would indeed be a good idea :D (updated)

  3. simon
    Posted January 4, 2010 at 8:17 am | Permalink

    nice way to get a stack overflow error if i is too big

  4. Posted January 11, 2010 at 7:34 pm | Permalink

    I`m not sure, but I think, “for” or “while” loops will work much faster becouse of bytecode architecture….
    In this case this snippet is an bad case of usage of language structures.

  5. Posted January 11, 2010 at 8:31 pm | Permalink

    Hey Peko… I completely agree with you.. recursion is not a good idea in ActionScript… it works wonders in other languages though…

    To quote this post (see above) : “Recursion is pretty useless in actionscript”

  6. Posted January 11, 2010 at 8:32 pm | Permalink

    also peko, see the warning page
    http://actionsnippet.com/?page_id=167

  7. raptros-v76
    Posted January 19, 2010 at 10:15 pm | Permalink

    Haskell, as a functional language, is heavily optimized for tail recursion, while imperative languages tend to have optimized looping constructs. Also, Haskell compiles to machine code.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*