Enums

  This was from H. Klawitter, in response to a question on how one would code up the notion of months in Sather.

Mainly there are two possibilites. Using a nifty feature of the Sather Spec. or really implementing enumerations on ones own, which is not difficult, but a little bit work to write.

Easy Approach

class MONTHS
is
    const jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec;
end; -- MONTH

class USING_MONTHS
is
    include MONTHS;

    ...
      if month = dec then self.prepare_for_christmas end;
    ...
end; -- USING_MONTHS

See also the Sather 1.0 Spec, Page 11f. However, this kind of enums have disadvantages, as they are not distinguished from INTs. Moreover, you can't force special values to special names. In this case, jan would be equal to zero, and you usually do not want this.

Better Approach

If you want to have full type control, you have to write a value class like this:

value class ENUM
    -- This class is meant to be included into classes, which should behave 
    -- like enumerations, and provides the basic comparison routines.
is
    readonly attr int:INT;
    -- This attribute is also used for transforming an enumeration object into
    -- an INT-value.

    is_eq(i:SAME) is int=i.int end;
    is_neq(i:SAME) is int/=i.int end;

end; -- ENUM

value class MONTH
is
    include ENUM;

    create(i:INT):MONTH
        -- Makes a MONTH out of an INT.
        pre i>=1 and i<=12
    is
        return int(i)
    end;

    -- Now the enumeration "itself".
    jan:MONTH is return int(1) end;
    feb:MONTH is return int(2) end;
    ...
    dec:MONTH is return int(12) end;

end; -- MONTH

You can use this class in the following way:

    month: MONTH;
    month := MONTH::jan;           -- How to use the "jan" name.
    birth := month.jan;            -- This does the same job.
    month := #MONTH(3);            -- conversion INT->MONTH
    if month = MONTH::feb then ... end;
    if month.int = 3 then ... end; -- conversion MONTH->INT
The disadvantages are obvious: Much code to hack. Also MONTH should subtyped under $IS_EQMONTH and probably under many more types.

 

The Sather Library

This section was has no meat as yet.... The Sather library is available with the distribution and consists of a reasonable set of Container classes as well as a user interface library that is based on Tcl/Tk. Please look at the documentation available under the Gui subidirectory of the distribution. Before too long we hop to have better documentation of the library as well.

 


Benedict A. Gomes
Mon Apr 29 10:12:43 PDT 1996