Skip to content

Instantly share code, notes, and snippets.

@jasononeil
Last active January 2, 2016 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasononeil/8328885 to your computer and use it in GitHub Desktop.
Save jasononeil/8328885 to your computer and use it in GitHub Desktop.
`AcceptEither`, a way to accept either one type or another, without resorting to "Dynamic", and still have the compiler type-check everything and make sure you correctly handle every situation.
class Test {
static function main(){
stringOrInt( "hello" );
stringOrInt( 10 );
}
static function stringOrInt( either:AcceptEither<String,Int> ) {
switch either.type {
case Left(str): trace("string: "+str);
case Right(int): trace("int: "+int);
}
}
}
abstract AcceptEither<A,B> (Either<A,B>) {
public inline function new( e:Either<A,B> ) this = e;
public var value(get,never):Dynamic;
public var type(get,never):Either<A,B>;
inline function get_value() switch this { case Left(v) | Right(v): return v; }
@:to inline function get_type() return this;
@:from static function fromA( v:A ):AcceptEither<A,B> return new AcceptEither( Left(v) );
@:from static function fromB( v:B ):AcceptEither<A,B> return new AcceptEither( Right(v) );
}
enum Either<A,B> {
Left( v:A );
Right( v:B );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment