Slot accessors
Factor handbook » The language » Objects » Tuples

Next:Tuple constructors

For every tuple slot, a reader method is defined in the accessors vocabulary. The reader is named slot>> and given a tuple, pushes the slot value on the stack.

Writable slots —- that is, those not attributed read-only —- also have a writer. The writer is named slot<< and stores a value into a slot. It has stack effect ( value object -- ). If the slot is specialized to a specific class, the writer checks that the value being written into the slot is an instance of that class first. See Tuple slot declarations for details.

In addition, two utility words are defined for each writable slot.

The setter is named >>slot and stores a value into a slot. It has stack effect ( object value -- object ).

The changer is named change-slot. It applies a quotation to the current slot value and stores the result back in the slot; it has stack effect ( object quot -- object ).

Since the reader and writer are generic, words can be written which do not depend on the specific class of tuple passed in, but instead work on any tuple that defines slots with certain names.

In most cases, using the setter is preferred over the writer because the stack effect is better suited to the common case where the tuple is needed again, and where the new slot value was just computed and so is at the top of the stack. For example, consider the case where you want to create a tuple and fill in the slots with literals. The following version uses setters:
<email> "Happy birthday" >>subject { "" } >>to "" >>from send-email

The following uses writers, and requires some stack shuffling:
<email> "Happy birthday" over subject<< { "" } over to<< "" over from<< send-email

Even if some of the slot values come from the stack underneath the tuple being constructed, setters win:
<email> swap >>subject swap >>to "" >>from send-email

The above has less shuffling than the writer version:
<email> [ subject<< ] keep [ to<< ] keep "" over from<< send-email

The changer word abstracts a common pattern where a slot value is read then stored again; so the following is not idiomatic code:
find-manager dup salary>> 0.75 * >>salary

The following version is preferred:
find-manager [ 0.75 * ] change-salary

See also
Low-level slot operations, Mirrors