Compare enum without considering its arguments
Asked Answered
M

3

5

Let me make this clear, I have this enum:

enum Token {
    Number(v:Float);
    Identifier(v:String);
    TString(v:String);
    Var;
    Assign;
    Division;
    // and so on
}

I want to check if the value of a variable is an Identifier, but this doesn't work:

if(tk == Token.Identifier) {

It only allows me to compare the values if I pass arguments:

if(tk == Token.Identifier('test')) {

But this will only match if the identifier is 'test', but I want to match any identifier.

Marvismarwin answered 22/9, 2010 at 16:31 Comment(0)
T
5
Type.enumConstructor(tk) == "Identifier"

Read the Type doc for more methods on enum.


Update (2019-02-04):

At the time of writing this answer it was still Haxe 2.06. Much have changed since then.

At this moment, for Haxe 3 (or 4), I would recommend pattern matching, specifically using single pattern check instead:

if (tk.match(Identifier(_)) ...

which is a short hand for

if (switch tk { case Identifier(_): true; case _: false; }) ...

_ is the wildcard that matches anything.

Timepiece answered 22/9, 2010 at 17:36 Comment(0)
R
3

alternatively:

static function isIdentifier(token : Token) return switch(token) { case Token.Identifier(_): true; default: false; }

Using "using" you should also be able to do:

if(tk.isIdentifier()) {
Rules answered 22/9, 2010 at 19:7 Comment(0)
C
2

Or even:

tk.match(Token.Identifier(_));
Camelot answered 4/12, 2015 at 21:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.