Sunday, January 29, 2012

Recursion and it's contribution to function abstraction


Recursion (if you are not familiar with what it is, then become familiar) is a method of programming that has made it easier to write simple and optimized functions. The positive aspect of recursion is the fact that it is a mechanism  that protects the programmer from making more mistakes and writing code that is unmanageable. As you can see, from the examples below, that the difference in clarity is big, even in these poor examples. Although, there is a hurdle to get over for those that are novices in programming, to understand recursive functions.

None Recursive Function (Ruby):
def bruteforce_nth_power(base, exponent)
    total = base
    (exponent-1).times do
        total *= base
    end 
    if exponent == 0
        return 1
    else
        return total
    end
end

Recursive Function (Ruby):
def reducebyone_nth_power(base, exponent)
    if exponent == 0
        return 1
    elsif exponent == 1
        return base
    else
        return base * reducebyone_nth_power(base, exponent-1)
    end
end

No comments:

Post a Comment