www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to print current type of a SumType?

reply Chris Piker <chris hoopjump.com> writes:
Hi D

I've a simple question but it's bedeviling me anyway.  How do I 
get a string representation of the current type of a SumType?  
I'm trying to avoid something like this:

```d
alias Vec3 = SumType!(void* /* invalid vector */, byte[3], 
short[3], char[][3]);

string prnType(Vec3 vec){

   return vec.match!(
      (void* _) => "void*",
      (byte[3] _) => "byte[3]",
      (short[3] _) => "short[3]",
      (char[][3] _) => "char[][3]"
   );
}
```

I'm sure there's a much easier way, especially once there's a 
largish number of vector types.

Thanks,
Sep 30 2023
next sibling parent Chris Piker <chris hoopjump.com> writes:
On Sunday, 1 October 2023 at 01:17:50 UTC, Chris Piker wrote:
 ```d
 alias Vec3 = SumType!(void* /* invalid vector */, byte[3], 
 short[3], char[][3]);

 ```
I know it's bad form to reply to my own question, but I think I found a reasonably simple way: ```d string prnType(Vec3 vec){ return vec.match!( t => typeof(t).stringof); } ``` which is hardly worth making into a function of it's own. Other suggestions are welcome of course. SumTypes are really tripping me up. Unlearning years of writing C takes more time then I'd prefer.
Sep 30 2023
prev sibling parent reply Paul Backus <snarwin gmail.com> writes:
On Sunday, 1 October 2023 at 01:17:50 UTC, Chris Piker wrote:
 Hi D

 I've a simple question but it's bedeviling me anyway.  How do I 
 get a string representation of the current type of a SumType?  
 I'm trying to avoid something like this:

 ```d
 alias Vec3 = SumType!(void* /* invalid vector */, byte[3], 
 short[3], char[][3]);

 string prnType(Vec3 vec){

   return vec.match!(
      (void* _) => "void*",
      (byte[3] _) => "byte[3]",
      (short[3] _) => "short[3]",
      (char[][3] _) => "char[][3]"
   );
 }
 ```

 I'm sure there's a much easier way, especially once there's a 
 largish number of vector types.

 Thanks,
```d return vec.match(value => typeof(value).stringof); ```
Sep 30 2023
parent Chris Piker <chris hoopjump.com> writes:
We posted at the same time!  Thanks for help nonetheless.

I do hope over time, SumTypes get the Ali Çehreli treatment.  I 
keep his book open on my desk all the time.
Sep 30 2023