AdeptLanguage / Adept

The Adept Programming Language
GNU General Public License v3.0
119 stars 8 forks source link

Feature request: switch expression #343

Open Apis035 opened 4 weeks ago

Apis035 commented 4 weeks ago

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".

IsaacShelton commented 3 weeks ago

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)
}
Apis035 commented 3 weeks ago

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?

IsaacShelton commented 3 weeks ago

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.