I have AS3/PHP background and some basic understaning of enums from C++. Saying shortly: I read this:
And though – good heavens! What the sorcery is this???
Enum Constructors Parameters?
Enum Type Parameters??
Could someone explain with working examples (preferable on http://try.haxe.org/ ) the concept of enums in HaXe for someone coming from languages like PHP and AS3?
What I tried?
Firstly I wrote this:
enum Color3 {
Red;
Green;
Blue;
Grey( v : Int );
Rgb( r : Int, g : Int, b : Int );
Alpha( a : Int, col : Color3 );
}
Then this:
Color3.Grey(5);
And I don't know what to do with this further, and don't know where to search.
Best Answer
HaXe enums are algebraic data types (ADTs). Your example in Haskell:
In either language, this type simply expresses that a
Color3
has a few possible values—red, green, or blue; a grey value; an arbitrary RGB value; or aColor3
value with an additional alpha channel. The fact that some of these constructors take extra parameters should not be alarming. It is simply a terse closed analog to the open behaviour of inheritance:Here anyone can come along and add a new
Color3
child class that may or may not respect the properties we want to enforce. With parameterised enums we have central control over all the constructors, and we also have pattern matching:Contrast the alternative of adding a
toInt()
method to every subclass ofColor3
. It would be much more code, leading to more potential for errors.Note that this particular example isn’t great because a few of the constructors are redundant:
Rgb
subsumesRed
,Green
,Blue
, andGrey
, andAlpha
can be applied to a colour that already hasAlpha
, which may not be desirable.