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
  end
end
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.

Thursday, June 5, 2008

Targetting IE7 with CSS

I've needed to target IE6 & IE7 within my css for 1 margin rule, so rather than some convoluted process I used the following simple hack

div#div_id{
margin: 10px 10px 5px 10px;
*margin: 10px 10px 10px 10px; /* Targets IE6 & IE7 */
_margin: 5px 5px 5px 5px; /* Targets IE6 */
}

Yes it is invalid CSS, but I don't really care, it's 1 - 2 lines in a 200 line stylesheet.