Tuesday, June 17, 2008

Functional Ruby methods

Ruby is a great language and normally I'd roll it in a object oriented fashion, however I've just started looking at Haskell, and thought that lambda could give me something similar to Haskell functions in Ruby. albeit without a ton of Haskell's features.

So here are two examples, the first is normal OOP Ruby

b = Time.now
class Integer
  def main
    self * self
1000000.times{ |i| i.main }
puts "Time: #{Time.now - b}"

On my machine this returns "Time: 1.115471"

Here is a functional style version.

b = Time.now
main = lambda { |x| x * x }
1000000.times &main
puts "Time: #{Time.now - b}"

First thing to note is that it's only 4 lines of code, not 8. Second thing is that it returns the following to the terminal:
"Time: 0.960359"

That's 0.155112 faster, just over 15% faster in computing a simple algorithm like this. Of course this is where functional programming is meant to shine, this is simply an experiment to see if I could do this is Ruby, it is hardly a well tested benchmark, and the results are not all together unexpected, but it's cool in any case.

No comments: