when pattern matching comes to a surprise

86 views
Skip to first unread message

Adrian Veith

unread,
Sep 20, 2017, 8:19:07 AM9/20/17
to Haxe
Hi List,

just stumbled upon a gotcha with pattern matching, which I wanted to share. We have a new coworker, who starts working with Haxe. He wrote some code, like the snippet below. In the case of the "h" he omitted the quotes and to my surprise the code did compile. It took me a while to grasp that pattern matching did its magic here:

class Test {
    static function main() {
        var input = "x";
        var answer = "";
        switch (input) {
           case "l":
                answer = "input was l";
           case h:
                answer = "input was h";
           default:
                answer = "dont know";
        }
        trace(answer); // "input was h"
    }
}
 


this can lead to nasty errors. Imagine this:

class Test {
    static inline var keyUP = "u";
    static inline var keyDOWN = "d";
    
    static function main() {
        var input = "d";
        var answer = "";
        switch (input) {
           case keyUPS:
                answer = "input was up";
           case keyDOWN:
                answer = "input was down";
           default:
                answer = "dont know";
        }
        trace(answer); // "input was up"
    }
}


now I know, that it is they way it is. Constants should be UPPERCASE !

Simon Krajewski

unread,
Sep 20, 2017, 8:28:07 AM9/20/17
to haxe...@googlegroups.com
Am 20.09.2017 um 14:19 schrieb Adrian Veith:
Hi List,

just stumbled upon a gotcha with pattern matching, which I wanted to share. We have a new coworker, who starts working with Haxe. He wrote some code, like the snippet below. In the case of the "h" he omitted the quotes and to my surprise the code did compile. It took me a while to grasp that pattern matching did its magic here:

class Test {
    static function main() {
        var input = "x";
        var answer = "";
        switch (input) {
           case "l":
                answer = "input was l";
           case h:
                answer = "input was h";
           default:
                answer = "dont know";
        }
        trace(answer); // "input was h"
    }
}
 


This should give you a warning about an unused case though.

Simon

Adrian Veith

unread,
Sep 20, 2017, 9:29:33 AM9/20/17
to Haxe
Yeah, maybe we need a warning to read the warnings ;)

Benjamin Dasnois

unread,
Sep 20, 2017, 11:03:21 AM9/20/17
to haxe...@googlegroups.com
It's a feature, not a bug.

Sorry, had to write it. Oh and by the way : I'm back! ;D

--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/d/optout.



--
Reply all
Reply to author
Forward
0 new messages