On Thursday, 31 July 2014 at 15:03:09 UTC, Justin Whear wrote:
On Thu, 31 Jul 2014 11:42:20 +0000, Remo wrote:

http://tech.esper.com/2014/07/30/algebraic-data-types/

D already has product type it is struct.
But D lacks sum type also called tagged-union.

Do you think it would be possible to add something like this to D2 ?

In addition to the suggestions of Algebraic or Variant elsewhere in this thread, it's trivial to implement your own concrete tagged unions:

struct MyTaggedUnion
{
   enum Type { Int, Float, String }
   Type tag;

   union {
      int int_;
      float float_;
      string string_;
   }
}

You can also hide the union members with private and only allow access
via property getters that check the tag.

Thanks for all the answers !

it's trivial to implement your own concrete tagged unions
Yes this is also possible to do in C++ too.
But I do not think that this is trivial at least not for 10 or 20 values. Enum and Union need always to be in sync and compiler will not output error if the programmer/user will make any mistake.

How to translate this useless Rust code to D, with as least D code as possible ? How be sure that everything will still work as expected if programmer will add White color ?

  enum Color {
    Red,
    Green,
    Blue,
    Rgb(int,int,int)
  }

  fn main() {
    let r = Rgb(64,128,255);
    match r {
      Red   => println!("Red"),
      Green => println!("Green"),
      Blue  => println!("Blue"),
      Rgb(r,g,b)   => println!("Rgb({},{},{})",r,g,b),
    }
  }

Reply via email to