Easy (and probably dumb) question re: switch()

Asinine

New member
Heya, for the life of me I cannot remember (and I'm apparently failing on finding examples)...

I want to run a switch statement with numerical ranges. Example: I want it to do function x for range 1-10, function y for range 11-20, and default function z.
What is the syntax for case?

All I could remember was
Code:
case 1..10: func_x();
break;
case 11..20: func_y();
break;
default: func_z();
break;
etc. But that doesn't work.

Help?
And thanks in advance...
 
Bale's code is the best way given your first example, but under other circumstances one could also use plural typed constants:

PHP:
int x = 15;
boolean[int]range = $ints[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

switch{
    case $ints[11, 12, 13, 14, 15] contains x: 
        print("func_x"); break;
    case range contains x: 
        print("func_y");break;
    default: 
        print("func_z"); break;
}
 

heeheehee

Developer
Staff member
Yet another alternative -- creating functions to mimic other languages:
PHP:
int range(int a, int b)
{
    boolean[int] map;
    for i from a to b
        map[i] = true;
    return map;
}
Then you can do stuff like
PHP:
switch{
    case range(1,10) contains x: 
        func_x();
        break;
    case range(11,20) contains x: 
        func_y();
        break;
    default: 
        func_z();
}
You could probably also do a foreach i in range(1,10) sort of thing, which would be significantly more useful, but it's not really any different (aside from time -- this is twice as slow) from using for i from 1 to 10, which is basically how it's implemented.
 
Last edited:

heeheehee

Developer
Staff member
Erm, yeah, wrong type used for the function declaration. My bad.

But as mentioned, my solution'd probably be best for folks learning to transition from some other language (i.e. Python), as it's nowhere near efficient.
 
Code:
case 1..10: func_x();
break;
case 11..20: func_y();
break;
default: func_z();
break;

This was one of the saddest moments for me when transitioning from Pascal's "case ... of" to C's "switch ... {case}"

ASH allows us to use non-ordinal types, which is nice, and makes the inability to use ranges understandable. C never had an excuse.
 
Top