Last active
May 9, 2016 19:38
-
-
Save ousado/9e38931c1380025ba459 to your computer and use it in GitHub Desktop.
GADT typed Anons/Classes/
This file contains 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
typedef DTag = Tag<Dynamic>; // kind of a defeat, but OK.. | |
typedef Fruit = { tag: TagE<Fruit>, name: String, count: Int } | |
typedef Beverage = { tag: TagE<Beverage>, name: String, brand: String, liters: Float}; | |
@:enum abstract TagE<T>(Int) { | |
var fruit: TagE<Fruit> = 1; | |
var beverage:TagE<Beverage> = 2; | |
} | |
typedef Tag<T> = { tag:TagE<T> }; | |
class Test { | |
static var data : Array<DTag> = [ | |
({ tag: fruit, name: "Apple", count: 5 } : Fruit ), | |
({ tag: fruit, name: "Orange", count: 3 } : Fruit ), | |
({ tag: beverage, name: "Sprite", brand: "Coca-Cola", liters: 2.5 } : Beverage ) | |
]; | |
static function resolve_tag<T:Tag<T>>(t:T) switch t.tag { | |
case fruit: | |
trace('${t.count} ${t.name}(s)'); | |
case beverage: | |
trace('${t.liters} liters of ${t.name}'); | |
} | |
static function main() for (item in data) resolve_tag( item ); | |
} |
This file contains 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
// using plain enum | |
enum Tag<T> { | |
a:Tag<Int>; | |
b:Tag<String>; | |
} | |
// also works with @:enum abstract | |
@:enum | |
abstract Tag2<T>(Int) { | |
var a2:Tag2<Int> = 1; | |
var b2:Tag2<String> = 2; | |
} | |
// class version | |
@:publicFields | |
class Tagged<T,U:Tag<T>> { | |
var tag:U; | |
var v:T; | |
function new(v:T,tag:U){ | |
this.tag = tag; | |
this.v = v; | |
} | |
} | |
typedef T1<T> = Tagged<T,Tag<T>>; | |
// anon version | |
typedef Tagged2<T> = { | |
tag : Tag2<T>, | |
v : T | |
} | |
class Test2 { | |
static function tigtag<T>(t:T1<T>){ | |
switch t.tag { | |
case a: | |
$type(t.v); | |
var i:Int = t.v; | |
trace(t.v); | |
case b: | |
$type(t.v); | |
var s:String = t.v; | |
trace(t.v); | |
} | |
} | |
static function tigtag2<T>(t:Tagged2<T>){ | |
switch t.tag { | |
case a2: | |
$type(t.v); | |
var i:Int = t.v; | |
trace(t.v); | |
case b2: | |
$type(t.v); | |
var s:String = t.v; | |
trace(t.v); | |
} | |
} | |
static function main() { | |
trace("Haxe is great!"); | |
tigtag( new Tagged(123,a) ); | |
tigtag( new Tagged("stttringgg..",b) ); | |
tigtag2( {v:123,tag:a2} ); | |
tigtag2( {v:"string",tag:b2} ); | |
// wrong usage: | |
// tigtag2( {v:1.2,tag:b2} ); // Tag2<String> should be Tag2<Float> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment