AssemblyScript / assemblyscript

A TypeScript-like language for WebAssembly.
https://www.assemblyscript.org
Apache License 2.0
16.62k stars 649 forks source link

Support more types in switch conditions #648

Open trusktr opened 5 years ago

trusktr commented 5 years ago

I've got some variables all of the same type, and I'm trying to use them in a switch, something like:

const f: f64 = 1.3
const g: f64 = 2.4

switch(f) {
  case g: ...; break
}

but it result in an error like

ERROR AS200: Conversion from type 'f64' to 'u32' requires an explicit cast.
Here's the whole code: ```ts getHSL(target: HSL): HSL { // h,s,l ranges are in 0.0 - 1.0 const r: f64 = this.r, g: f64 = this.g, b: f64 = this.b let max: f64 = Math.max(r, g) max = Math.max(max, b) let min: f64 = Math.max(r, g) min = Math.min(min, b) let hue: f64 = 0 let saturation: f64 = 0 const lightness: f64 = (min + max) / 2.0 if (min === max) { hue = 0 saturation = 0 } else { const delta = max - min saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min) switch (max) { case r: hue = (g - b) / delta + (g < b ? 6 : 0) break case g: hue = (b - r) / delta + 2 break case b: hue = (r - g) / delta + 4 break } hue /= 6 } target.h = hue target.s = saturation target.l = lightness return target } ```
and the error output: ``` ERROR AS200: Conversion from type 'f64' to 'u32' requires an explicit cast. switch (max) { ~~~ in src/as/glas/math/Color.ts(559,11) ERROR AS200: Conversion from type 'f64' to 'u32' requires an explicit cast. case r: ~ in src/as/glas/math/Color.ts(560,9) ERROR AS200: Conversion from type 'f64' to 'u32' requires an explicit cast. case g: ~ in src/as/glas/math/Color.ts(563,9) ERROR AS200: Conversion from type 'f64' to 'u32' requires an explicit cast. case b: ~ in src/as/glas/math/Color.ts(566,9) ```
willemneal commented 5 years ago

Hmm, I've never encountered switching on a floating point number before. I'm not sure it's well specified since floating point equality is not precise. I would switch to using if/elses.

trusktr commented 5 years ago

That's what I ended up doing, but seems like the switch should use the same underlying equality check (probably using ==).

But even with conditionals, I'm having problems with the above code, I'm porting the code (and its tests) from JS to AS, but in AS I'm getting different values, and the tests are failing.

MaxGraey commented 5 years ago

You could rewrite it to:

switch (true) {
  case max == r:
    hue = (g - b) / delta + (g < b ? 6 : 0)
    break
  case max == g:
    hue = (b - r) / delta + 2
    break
  case max == b:
    hue = (r - g) / delta + 4
    break
}
ColinEberhardt commented 3 years ago

+1 for supporting switch/case with string values