Created
July 17, 2009 10:20
-
-
Save saivenkat/148993 to your computer and use it in GitHub Desktop.
Tail recursion in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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