Welcome to Dream.In.Code
Getting Help is Easy!

Join 107,426 Programmers for FREE! Ask your question and get quick answers from experts. There are 1,249 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Tail Recursion vs. Tree Recursion

 
Reply to this topicStart new topic

Tail Recursion vs. Tree Recursion

spullen
post 9 Oct, 2007 - 10:00 PM
Post #1


D.I.C Regular

Group Icon
Joined: 22 Mar, 2007
Posts: 330



Dream Kudos: 50
My Contributions


I have been taking a course on programming paradigms and one thing that we have learned about is different types of recursion. I really never thought about a different way to write recursive functions until I saw tail recursion.
So here is a little test with Ruby and the differences between tree and tail recursion and the most basic recursive methods (factorial). Notice the execution times.
CODE

def tailFactorial(n, result)
  if n == 1
    return result
  else
    tailFactorial((n - 1), (result * n))
  end
end

def factorial(n)
  if n == 1
    return 1
  else
    return n * factorial(n-1)
  end
end

puts "Here is a tail recursive approach to the factorial problem\n"
puts tailFactorial(8, 1)

puts "\n"
puts "Here is a tree recursive approach to the factorial problem\n"
puts factorial(8)

puts "\nExecution times\n"
puts "Tree recursion: \n"
st = Time.now
result = factorial(8)
tt = Time.now - st
puts "Tree recursive approach, 8! = " + result.to_s + ", and was done in " + tt.to_s + "\n"
puts "Tail Recursion: \n"
st = Time.now
result = tailFactorial(8, 1)
tt = Time.now - st
puts "Tail recursive approach, 8! = " + result.to_s + ", and was done in " + tt.to_s + "\n"


The reason tail recursion has a faster execution time is because it doesn't have to pop anything off the stack to get the result. The result is just passed as a parameter into the method.

BTW, ruby tutorial section!!!
User is offlineProfile CardPM

Go to the top of the page


skyhawk133
post 9 Oct, 2007 - 10:01 PM
Post #2


Head DIC Head

Group Icon
Joined: 17 Mar, 2001
Posts: 14,423



Thanked 33 times

Dream Kudos: 1650

Expert In: Web Development

My Contributions


QUOTE
BTW, ruby tutorial section!!!


You gonna write the first few tutorials for it? smile.gif If so, I'll make it right now.
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 8/28/08 08:48PM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month