Skip to content

Instantly share code, notes, and snippets.

@saivenkat
Created July 17, 2009 10:20
Show Gist options
  • Save saivenkat/148993 to your computer and use it in GitHub Desktop.
Save saivenkat/148993 to your computer and use it in GitHub Desktop.
Tail recursion in ruby
def factorial_tail(number)
proc_fact = lambda do |acc, x|
if x <= 0
acc
else
proc_fact.call(x * acc, x - 1)
end
end
return proc_fact.call(1, number)
end
puts "Factorial using tail recursion - #{factorial_tail(10)}"
def fibonacci_tail(n)
fib_fact = lambda do |a,b,n|
if n <= 1
b
else
fib_fact.call(b, a + b, n -1)
end
end
return fib_fact.call(0, 1, n)
end
puts "Fibonacci series using tail recusrion - #{fibonacci_tail(10)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment