2007
05.06

Readability?

[source:ruby]
def factorial n
fac = 1
1.upto n do |i|
fac *= i
end
fac
end

def factorial n
fac = 1
for i in 1..n do
fac = fac * i
end
fac
end

def factorial n
fac = 1
1.upto n { |i| fac *= i }
fac
end

(defun factorial (n)
(loop for i from 1 to n
for fac = 1 then (* fac i)
finally (return fac)))
[/source]

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • HackerNews
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter

2 comments so far

Add Your Comment
  1. Missed a lightly optimised version:

    def factorial n
      r = 1
      n.downto(2) { |i| r *= i }
      r
    end
    

    and missed a ruby classic (Slower):

    def factorial n
      (2..n).inject(1) { |r, i| r *= i }
    end
    
  2. I should also note that a friend, who was an ex-Java now corporate web management head, found the Lisp style most readable!?

    We prefer the ruby style, with downto.