Haxe: Shorthand expression matching

This is a small post about a small, useful macro for Haxe.

As you may (or may not) know, Haxe has fancy enums (which are actually algebraic data types). That's nice. And you can do all sorts of fancy value matching on them, which is also nice.

What is less nice, however, is that the only conventional way to extract enum arguments is to "match" it, and thus in some situations you can only do code like this,

var r = switch (expr) {
    case one(k): k;
    default: -1;

adding a couple lines of code in place of what feels like it could have been a single operator.

So I wrote a tiny macro which adds just that:

var r = ematch(expr, some(k), k, -1);

Behind the scenes, the macro unpacks to a switch-block identical to what could have been handwritten. The code is incredibly straightforward:

public static macro function ematch(expr, match, then, ?not) {
    if (not == null) not = { expr: null, pos: null }; // alt., macro { }
    return macro switch ($expr) {
        case $match: $then;
        default: $not;

Here it replaces the optional "else"-argument with an blank expression if it wasn't specified, and outputs a switch-block with arguments added into it.

Same as with any other macros, you can also include blocks of expressions.

ematch(expr, some(k), {
    if (k < 0) return;

And that's it on usage. While it would have been nice to see something like this implemented in the language itself, personally I can't think of any remotely appropriate syntax. But this works too.

Have fun!

Related posts:

2 thoughts on “Haxe: Shorthand expression matching

    • Sure. It was also pointed out that there’s this snippet on there, which offers a slightly more obvious syntax for situations when an else-expression is not needed.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.