Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Recursive function needs a return statement?
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
boogerlad




PostPosted: Sat Feb 04, 2012 11:37 am   Post subject: Recursive function needs a return statement?

what's the difference
http://pastebin.com/331rMxcX
http://pastebin.com/ArwRs0h7

between those two? In the (recursive?) method "conversion", at the end
of an if, there is

return conversion(old);

and in the other version of the same program just

conversion(old);

Is there a difference in performance/syntax? Would this method even be
considered as recursion? Thanks again!
Sponsor
Sponsor
Sponsor
sponsor
Insectoid




PostPosted: Sat Feb 04, 2012 12:12 pm   Post subject: RE:Recursive function needs a return statement?

Both are essentially the same. The first runs conversion() and returns the result (old) right away, inside the if block. The other runs conversion() and then returns old at the bottom of the function.

[code]
function foo(a){
if (a) return a + 1;
}
//this is the same as:
function baz (a){
if (a) a += 1;
return a;
}

If Java supports tail-recursion optimization (I dunno if it does), then the first function will be much more efficient. Otherwise, they're the same.
boogerlad




PostPosted: Sat Feb 04, 2012 10:17 pm   Post subject: RE:Recursive function needs a return statement?

ah, I see. Would http://pastebin.com/n6gMP18J be preferred because it's cleaner? Also, my google fu skills are weak, but can you explain tail recursion?
Insectoid




PostPosted: Sat Feb 04, 2012 11:25 pm   Post subject: RE:Recursive function needs a return statement?

http://en.wikipedia.org/wiki/Tail_call

Basically, tail recursion is when the very last thing the function does is return the function call. This can be optimized in the build depending on the language and compiler, since you don't need to remember the stack. Regular recursion will build a copy of the function in RAM for each recurse- a function that recurses 10 times will have 10 copies of the function in RAM. With a tail call, since it's the last thing the function does, the function stack resets and is just re-run with the new input, so it only requires one copy of the function. In other words, it turns the recursive function into a loop.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: