An example of using a case statement in J.

NB.* RatingCase: characterize type of bond based on short designation.
RatingCase=: 3 : 0
   btype=. ''
   select. toupper y
       case. 'AAA';'AA';'A' do. btype=. 'Senior: '
       case. 'BBB';'BB';'B' do. btype=. 'Junior: '
       case. 'CCC';'CC';'C' do. btype=. 'Low-grade: '
       case. 'D' do. btype=. 'Defaulted: '
       fcase. 'GNMA' do. btype=. 'Government-guaranteed '
       fcase. 'FHMLC';'FNMA' do. btype=. btype,'Agency '
       case. 'MBS';'RMBS' do. btype=. btype,'Mortgage-backed: '
       case. do. btype=. 'Don''t know: '
   end.
   btype,y
)

   RatingCase 'FNMA'
Agency Mortgage-backed: FNMA
   RatingCase 'GNMA'
Government-guaranteed Agency Mortgage-backed: GNMA
   RatingCase 'MBS'
Mortgage-backed: MBS
   RatingCase 'AAA'
Senior: AAA
   RatingCase 'AAAA'
Don't know: AAAA
   RatingCase 'b' 
Junior: b
   RatingCase 'd' 
Defaulted: d

As can be seen, "fcase." drops through whereas "case." completes and exits.

At first, it might seem puzzling that 'GNMA' triggers all three of the actions below it (since it does not match the following conditions) but this is by design. It's as though a sequence of "fcase"s with a terminal "case" has an implicit "or". If it were otherwise, you'd have to duplicate the previous conditions to achieve what it does, e.g. to accomplish what this does now, e.g. for:

fcase. 1 do. smoutput 'one'
fcase. 2 do. smoutput 'one or two'
case.  3 do. smoutput 'one or two or three'

you'd need to code it like this:

fcase. 1 do. smoutput 'one'
fcase. 1;2 do. smoutput 'one or two'
case.  1;2;3 do. smoutput 'one or two or three'

and so on with the condtion getting arbitrarily longer if there were further, more general groupings.

The example above shows why you might use it this way: you've got logically nested classes and you want to show the more general categories which include the more specific cases. As you move down the sequence of "fcase." statements, you go from specific to more general.

DevonMcCormick/CaseStatementExample (last edited 2008-12-08 10:45:51 by )