Skip to content

Instantly share code, notes, and snippets.

@player-03
Last active August 29, 2015 14:27
Show Gist options
  • Save player-03/03a9fe219351674a8e36 to your computer and use it in GitHub Desktop.
Save player-03/03a9fe219351674a8e36 to your computer and use it in GitHub Desktop.
A macro for finding the first non-null item in a list without evaluating any items after that one.
import haxe.macro.Expr;
class OrMacro {
/**
* @return The first non-null argument.
*/
public static macro function or(options:Array<Expr>):Expr {
var ifElseStatements:Expr = options[options.length - 1];
var i:Int = options.length - 1;
while(i --> 0) {
ifElseStatements = macro if((temp = ${options[i]}) != null)
temp;
else
$ifElseStatements;
}
return macro {
var temp;
$ifElseStatements;
};
}
//Normally, macros should be placed in their own class. However, since
//this example is very simple (that is, it requires no imports), it's
//safe to leave it here.
public static function main():Void {
//The or() function won't make any extraneous function calls.
trace(or(returnNull(), returnString(), returnString()));
//returnNull() was called.
//returnString() was called.
//This is a string.
//If the last value is reached, it will be returned as-is.
trace(or(returnNull(), returnNull()));
//returnNull() was called.
//returnNull() was called.
//null
//or() can be used anywhere a normal function can be.
trace(or("Hello, world.", null) == "Hello, world.");
//true
}
public static function returnNull():String {
trace("returnNull() was called.");
return null;
}
public static function returnString():String {
trace("returnString() was called.");
return "This is a string.";
}
}
@player-03
Copy link
Author

The MIT License (MIT)

Copyright (c) 2015 Joseph Cloutier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment