|Deletions are marked like this.||Additions are marked like this.|
|Line 22:||Line 22:|
|The empty "case." at the end catches anything not matching the preceding ones. It's good coding practice to '''always''' include a final statement of this type.|
The "case" statement, being keyword-based, is not a very J-like construction. Take a look here for a suggestion on how to use gerunds with the "agenda" conjunction as an equivalent that better fits the functional paradigm.
However, if you must, here's 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 )
The empty "case." at the end catches anything not matching the preceding ones. It's good coding practice to always include a final statement of this type.
Here's some examples of how this works in practice.
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.
See Dan's comment on how the "case" statement might be extended.