Ultimate CASE Statement#

by Wil Baden, Costa Mesa, California

appeared in VD February 1987

Many citizens of the Forth community have lamented the lack of a case statement in standard Forth language specifications. Since the first rule of Forth programming is, "If you don't like it, change it," there have been many proposals, and Forth Dimensions even held "The Great CASE Contest in Volume II". Although the winning entry of that contest, submitted by Charles Eaker, has been widely implemented and even offered as part of many vendors' systems, the flood of proposals has not ceased. There have been many articles and letters on the subject in Forth Dimensions.

All proposals to date have had problems. Portability is one. Another is that they all have been too specialized and restricted in their area of application. Generalization is accomplished by designing another special case of case.

Strictly speaking, a case statement is unnecessary. It is " syntactic sugar" to make a program easier to write, read and understand. It is so helpful in doing this that it is a standard feature of all other modern programming languages.

Figure 1a

craps (n) 
int n;
{   if (n==7) printf ("You win");
    else if (n == 11) printf ("You win");
    else if (n == 2)  printf ("You lose"); 
    else if (n == 3)  printf ("You lose"); 
    else if (n == 12) printf ("You lose"); 
    else printf ("%d is your point",n);
}

Figure 1a is a rather futile program written in C to illustrate a common pattern of logical decisions in many programs.("==" is "equal to" for comparing two things, to distinguish it from "=" for assignment as in Fortran or Basic.) An equivalent Forth version would look something like Figure 1b.

Figure 1b

: CRAPS ( n -- ) 
  DUP 7 =
  IF DROP ." You win" 
  ELSE DUP 11 =
    IF DROP ." You win" 
    ELSE DUP 2 =
      IF DROP ." You lose" 
      ELSE DUP 3 =
        IF DROP ." You lose" 
        ELSE DUP 12 =
          IF DROP ." You win"
          ELSE . ." is your point" THEN 
          THEN THEN THEN THEN THEN ;

Most people will agree that Figure One-a would be better written as in Figure Two-a A n even better way is found in some dialects of C, illustrated by Figure Tivo-b. In this extension, following syntax from Pascal, values separated by "," indicate a set of v alues, and values separated by " . . " indicate a range. Some Forth proposals have one def­ inition for individual values and anoth­ er definition for a range of values. There would have to be another defini­ tion for a set of values. No earlie