Tuesday, February 19, 2008

Boxes

Today I was looking over some code and noticed a repetitive pattern involving tuple slots that would come up again and again:
  • One word would check if the slot was set; if not, it would throw an error, otherwise it would return the slot's value and set the slot's value to f.
  • Another word would check if a slot was set, and if so, throw an error, otherwise store the top of the stack in the slot.

I decided to abstract this out into a new "box" data type. A box can hold a single value; storing a value into a full box, or taking a value out of an empty box is an error, and taking a value out empties the box. Now the idea is that you set a tuple slot to a new box once in the constructor, and then instead of reading and writing the tuple slot you read and write the box.

I've already found several uses for this in the core/ as well as some of my libraries in extra/. I've not seen the box type in other object-oriented languages. It seems like an obvious abstraction; maybe it is considered too simple by some, but its nice to encapsulate this logic in one place. Factoring it out also let me make the logic more sophisticated: it can distinguish between a box holding f and an empty box. Most individual usages didn't bother. When Factor moves to native threading boxes will be even more valuable since boxes will be atomic.

3 comments:

Anonymous said...

Scala' Option; Haskell's Maybe; AliceML's futures (these have a lot of concurrency logic in them, with multiple forms).

Slava Pestov said...

Anonymous: Haskell's Maybe is immutable.

Kevin Reid said...

Sounds like Haskell's MVar.