I've been playing around with recursive functions in actionscript for a bit now and yesterday came across this pretty cool one for reversing a string. The code follows :
function Reverse(s : String ) : String { var tmp : String = null; if ( s.length == 1 ) return s; else { var sLast : String = s.substr( s.length -1, s.length ); var sRemainder : String = s.substr( 0, s.length -1 ); tmp = sLast + Reverse( sRemainder ); return tmp; } } var str : String = "abcdef"; trace( Reverse( str ) );
This little diagram I drew out helped me understand what the execution stack looked like :