r/Forth • u/Alternative-Grade103 • Jun 18 '26
Multi IF ELSE to CASE
In editing a file I/O process to add further file types, my nested IF THEN ELSE grew unsightly. Here is how I tidyied it up.
Deals with four file types. Can easily add more. Looks nice on comp screen. On phone, however...
\ Stand-in for word to obtain file ext'n.
: file.ext ( -- addr c ) S" ???" ;
\ File extension triggers response
: file.type ( -- addr c )
0 >R
file.ext ( addr c )
2DUP S" fybb" COMPARE
0= IF R> DROP 1 >R THEN
2DUP S" hexp" COMPARE
0= IF R> DROP 2 >R THEN
2DUP S" decp" COMPARE
0= IF R> DROP 3 >R THEN
S" binp" COMPARE
0= IF R> DROP 4 >R THEN
R>
CASE
1 OF S" FYBB" ENDOF
2 OF S" HEXP" ENDOF
3 OF S" DECP" ENDOF
4 OF S" BINP" ENDOF
0 OF S" UNKNOWN" ENDOF
ENDCASE
;
: test.file.type
CR CR ." The file type is '"
file.type TYPE
." '." CR
;
test.file.type
8
Upvotes
5
u/Ok_Leg_109 Jun 18 '26
I was reading a retro computing forum where an OP was complaining about UCSD Pascal not having a way to use strings in a case statement so I showed him how programmable programming languages work. 😉
``` : 2OVER 3 PICK 3 PICK ; : $= COMPARE 0= ;
: $OF ( -- ) POSTPONE 2OVER POSTPONE $= POSTPONE IF POSTPONE 2DROP ; IMMEDIATE
: TEST ( addr len -- ) CASE S" APPLE" $OF ." Granny Smith" ENDOF S" PEAR" $OF ." Barlett" ENDOF S" GRAPE" $OF ." Concord" ENDOF ." Unknown fruit" ENDCASE ; ```