Actionscript:
-
loop(20);
-
-
function loop(i:int):void {
-
if (i <0) return;
-
trace(i);
-
loop(i - 1);
-
}
-
-
/* outputs:
-
20
-
19
-
18
-
17
-
16
-
15
-
14
-
13
-
12
-
11
-
10
-
9
-
8
-
7
-
6
-
5
-
4
-
3
-
2
-
1
-
0
-
*/
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.
7 Comments
It might be a good idea to change:
if (i == -1)
to:
if (i < 0)
Otherwise loop(-2) will infinitely recurse.
that would indeed be a good idea (updated)
nice way to get a stack overflow error if i is too big
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.
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”
also peko, see the warning page
http://actionsnippet.com/?page_id=167
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.