Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Argument Switch Statement

So I was taking a Computer Science test today, and I had to write out a large number of consecutive if statements. All of them had the same basic arguments, just the conditions were different. The whole thing made me wonder if somewhere out there was a multiple argument switch statement. An example of what I'm thinking of is this:

int i = 7;

switch(i > 4, i < 10) {
    case T, T:
        return "between 4 and 10";

    case T, F:
        return "greater than 10";

    case F, T:
        return "less than 4";

    case F, F:
        return "your computer's thinking is very odd";
}

In this case, the arguments are i > 4 and i > 10, and the T and F are whether the argument is true or not.

I know this example can be easily done other ways, but I'm just trying to show its use. And what if there were 4 arguments, that would be something like 20 if statements each requiring you to retype the conditions.

So my question is, is there any language that does this? Or is it planned for a future language? Or does an even better method exist?

like image 283
Jon Egeland Avatar asked May 03 '11 16:05

Jon Egeland


2 Answers

It's hard to say that "no language does this" because there almost certainly is someone working on an experimental language or two that does. However, most procedural languages don't have this kind of feature.

In your example, I think you mean the T, F, etc. to mean "the first expression evaluates to True and the second evaluates to False" (that is, the , is logical AND). This is reminiscent of some decision table languages, where the processing involves finding the first row of a decision table that is satisfied and executing that row's action. Other than that, I don't know of any language that has anything like this.

like image 80
Ted Hopp Avatar answered Sep 28 '22 07:09

Ted Hopp


At least in languages that allow conversion from bool to int, you can handle this pretty easily. You basically just convert the two booleans into a bit-mapped integer value. Since you have two booleans, you can use one directly as bit 0 of your result, and the other multiplied by two as the second bit of your result.

int i = 7;

int range = (i>4) | (i<10)*2;

switch(range) {
    case 3: return "between 4 and 10";
    case 2: return "greater than 10";
    case 1: return "less than 4";
    case 0: return "your computer's thinking is very odd";
}
like image 29
Jerry Coffin Avatar answered Sep 28 '22 07:09

Jerry Coffin