2004-12-08

Deferring calculations in Ruby

It started with Patrick Logan: How would you implement spreadsheets as top-level programming objects? He's not talking about dropping a grid into your source file, but allowing deferred calculations. What he wants is the equivalent of something like this:



a = 10
b = a * 2
a = 15
puts b
>> 30

"Easy enough," I hear you say, "if you use a lambda (method object) for the value of b." Ah, but there are at least two wrinkles there. First, you need to write the value of b as a lambda, which requires more typing. Second, when you go to use b, how you use it depends on whether it's a constant or a lambda. The only easy way around the second wrinkle is to make all values lambdas, which brings us back to the first wrinkle. Patrick solves both of these problems by defining a Spreadsheet class that contains Cells that contain Formulas—all of which are smart enough to do the tedious stuff for you.


Fortunately (for those of us who aren't as fluent in Ruby as we'd like), Jim Weirich has provided a Ruby implementation.

0 Comments:

Post a Comment

<< Home