Last active
July 9, 2020 03:20
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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;} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
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
Updated with the code from Franco here https://twitter.com/fponticelli/status/671874376904523776 http://try.haxe.org/#c0557