Virtual Structs Part 1: Where Rust’s Enum Shines
smallcultfollowing.com
smallcultfollowing.com
I don't know what the language of the future will be but I can't imagine it not having an ML heritage.
That said, the language with the most powerful pattern matching engine I've used so far has been Erlang. Just about everything there is intimately tied to it, giving it a homoiconicity between the code and the literal data types. You can even pattern match on binary formats, like file headers or packet structures.
It seems like Algol-like languages are slowly absorbing lessons from ML. Rust is quite an evident example.
But algebraic data types do not in themselves provide a way to express the notion of a type with variants or sub-types.
The name is not used for the current "enum" feature, which is one of the few ADTs in Rust (there's also "struct" and tuples - not sure what else qualifies).
So it's a lot of boilerplate. I think it can be slimmed down with a macro, but still.
You might think traits rather than enums are the way to go here. Sometimes that may be true. But often, an enum is far preferable because in Rust, a trait is not a type, but an enum is. That means you cannot, for example, have a "Vec<CanineTrait>," but you can have a "Vec<CanineEnum>."
Also, I've been wondering something about dereferencing a Box where the inner type is just a trait. If I dereference a Box<CanineTrait> and call "bark," how is the correct implementation found at runtime? Is there a vtable or something analogous?
I think a vtable. It's my understanding that "trait objects" (boxed traits) are how you implement dynamic dispatch in rust. If instead you were talking about a `fn foo<T: CanineTrait>(x: T) { ... }` trait bound (the more common case), there will be monomorphization and static dispatch.
Source: http://doc.rust-lang.org/1.0.0-beta/book/static-and-dynamic-...
In cases like this I think it is better to call it by a more generic name rather than a specific name which it really subsumes (like Haskell using the `data` keyword for algebraic data type definitions).
They can in Java. Java's about as mainstream of a programming language as you can think of.
That is, Enum.A will always be Enum.A with the same data on it at all times in Java. This is not the case for ADTs.