Adept icon indicating copy to clipboard operation
Adept copied to clipboard

Feature request: switch expression

Open Apis035 opened this issue 1 year ago • 3 comments

For example, if I could write this code:

rateText String

switch rate {
    case 1 rateText = "Weak"
    case 2 rateText = "Moderate"
    case 3 rateText = "Strong"
    case 4 rateText = "Powerful"
    default rateText = "Unknown"
}

Into this:

rateText String = switch rate {
    case 1 "Weak"
    case 2 "Moderate"
    case 3 "Strong"
    case 4 "Powerful"
    default "Unknown"
}

It would make the code shorter to type as rateText is only typed once. Its also much nicer to look at.

Currently, typing this switch expression makes the compiler error "unexpected switch token in expression".

Apis035 avatar Jun 19 '24 04:06 Apis035

Yes I've also been wanting this.

There will be something similar supported in Adept 3.0 (this feature is already in progress for it)

In the meantime however, if your values are predicable, a function or table could work

func getRateText(rate int) String {
    switch rate {
        case 1, return "Weak"
        case 2, return "Moderate"
        case 3, return "Strong"
        case 4, return "Powerful"
    }

    return "Unknown"
}

---or---

func main {
    ratings <String> Array = {
        "Unknown",
        "Weak",
        "Moderate",
        "Strong",
        "Powerful",
    }

    rating int = 3

    // NOTE: By default, the feature `Array_bounds_checks` of `2.8/Array.adept` is true, so this will
    // panic if rating is out of range
    rating_text String = ratings.get(rating)
}

IsaacShelton avatar Jun 20 '24 05:06 IsaacShelton

Cool! I like the "array get" workaround, but obviously the rating variable shouldn't be out of bounds. I'll just clamp it, so it stays in range.

As for the switch expression, it will be available in Adept 3, but will you backport it to Adept 2? And when Adept 3 has been released, will Adept 2 still be maintained?

Apis035 avatar Jun 20 '24 09:06 Apis035

Adept 2 isn't designed to handle the semantics of it, so it's unlikely to be backported in the near term.

Adept 3 still has a lot of work going into it, and will probably take a year or two before it'll be ready enough to start being used. (There are a lot of major improvements and so takes awhile)

Adept 2 will still always be maintained including after its release, and will most likely receive additional improvements in the form of backported features and/or potentially support in the new compiler.

IsaacShelton avatar Jun 21 '24 17:06 IsaacShelton