Skip to content

Instantly share code, notes, and snippets.

@mrcdk
Last active July 9, 2020 03:20
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcdk/d881f85d64379e4384b1 to your computer and use it in GitHub Desktop.
Save mrcdk/d881f85d64379e4384b1 to your computer and use it in GitHub Desktop.
OneOf abstract: An abstract that uses haxe.ds.Either as its base type and hides the explicit use of it. http://try.haxe.org/#c0557
import haxe.ds.Either;
abstract OneOf<A, B>(Either<A, B>) from Either<A, B> to Either<A, B> {
@:from inline static function fromA<A, B>(a:A) : OneOf<A, B> return Left(a);
@:from inline static function fromB<A, B>(b:B) : OneOf<A, B> return Right(b);
@:to inline function toA():Null<A> return switch(this) {case Left(a): a; default: null;}
@:to inline function toB():Null<B> return switch(this) {case Right(b): b; default: null;}
}
class Test {
static function main() {
var a:OneOf<String, Int> = "hello";
trace(a);
a = 5;
trace(a);
var b:OneOf<Int, Bool> = true;
trace(b);
b = 4;
trace(b);
var c:OneOf<String, Float> = 5.5;
trace(c);
c = "hello";
trace(c);
// perfect for function parameters
function test(o:OneOf<String, Int>) {
switch(o) {
case Left(s): trace("Found a String: " + s);
case Right(i): trace("Found an Int: " + i);
}
}
test(a);
a = "hello";
test(a);
//test(b); // this won't work
//magic
test(100);
test("Magic");
//test(true); // this won't work
// also, casting:
trace("This should be null: " + (a:Int));
trace("This should be a string: " + (a:String));
//trace("This won't work: " + (a:Bool));
}
}
@mrcdk
Copy link
Author

mrcdk commented Dec 2, 2015

@jcward
Copy link

jcward commented Jun 23, 2017

Per my write-up and note that OneOf<A,B> isn't compatible with OneOf<B,A>, @kevinresol suggests:

@:to inline function swap():OneOf<B, A> return switch this {case Right(b): Left(b); case Left(a): Right(a);}

Looks like it works nicely: https://try.haxe.org/#53Fd0

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