Tuple examples
Factor handbook » The language » Objects » Tuples

Next:TUPLE:


An example:

TUPLE: employee name position salary ;


This defines a class word named employee, a predicate employee?, and the following slot accessors:
ReaderWriterSetterChanger
name>>name<<>>namechange-name
position>>position<<>>positionchange-position
salary>>salary<<>>salarychange-salary

We can define a constructor which makes an empty employee:

: <employee> ( -- employee ) employee new ;


Or we may wish the default constructor to always give employees a starting salary:

: <employee> ( -- employee ) employee new 40000 >>salary ;


We can define more refined constructors:

: <manager> ( -- manager ) <employee> "project manager" >>position ;


An alternative strategy is to define the most general BOA constructor first:

: <employee> ( name position -- employee ) 40000 employee boa ;


Now we can define more specific constructors:

: <manager> ( name -- employee ) "manager" <employee> ;


An example using reader words:

TUPLE: check to amount number ; SYMBOL: checks : <check> ( to amount -- check ) checks counter check boa ; : biweekly-paycheck ( employee -- check ) [ name>> ] [ salary>> 26 / ] bi <check> ;


An example of using a changer:

: positions ( -- seq ) { "junior programmer" "senior programmer" "project manager" "department manager" "executive" "CTO" "CEO" "enterprise Java world dictator" } ; : next-position ( role -- newrole ) positions [ index 1 + ] keep nth ; : promote ( employee -- employee ) [ 1.2 * ] change-salary [ next-position ] change-position ;


An example using subclassing can be found in Tuple subclassing example.