[Haskell-cafe] How to build a generic spreadsheet?

Sebastian Sylvan sebastian.sylvan at gmail.com
Fri Feb 23 17:59:44 EST 2007

On 2/23/07, Greg Fitzgerald <garious at gmail.com> wrote:
> I want to write a program where a user would update a bunch of variables,
> and everything that depends on those variables (and nothing else) are
> recalculated.  Basically, a spreadsheet, but generalized for any
> computation.  Could someone recommend an elegant way to do it or some good
> reading material?

Off the top of my head, one cool way of doing it would be to have each
variable be a separate thread (they're lightweight, so it's okay!
:-)), and you would have a list of input connections and output
connections, in the form of TVars.

In its resting state you would have a transaction which simply reads
all of the input variables, and returns the new list of inputs if and
only if either of them are changed, something like:

-- not compiled, consider it pseudocode :-)
getInputs :: (Eq a ) => [( a, TVar a)] -> STM [a]
getInputs inp = do
  let (vals, vars) = unzip inp
  newVals <- mapM readTVar vars
  when ( newVals /= vals ) retry -- at least one input must've been changed
  return vals

This takes a list of "current values" zipped with the corresponding
TVars, and would block until at least one input has changed.

So once you get the values back from the function above, you know one
of them has change, and you simply recompute the new value from the
inputs, and plug the output into the output TVars and all the
dependent "nodes" will automatically be unblocked and propagate its
changes by virtue of the GHC scheduler. No coding required! At this
stage you'd probably want to update some GUI control as well to
display the new state.

Sebastian Sylvan
UIN: 44640862

More information about the Haskell-Cafe mailing list