Tagged unions [Was: What's wrong with std.variant.Variant?]

Dukc ajieskola at gmail.com
Tue Jun 16 12:58:50 UTC 2020


On Tuesday, 16 June 2020 at 12:21:56 UTC, Paul Backus wrote:
> If it's not too much trouble, can you give an example of the 
> kind of thing you'd like to be able to do?

No problem. This is directly from real code. The idea is that I 
have a vector shape `vecImage.front` and I want to figure out 
whether I need to reverse it, so that it will run in wanted 
direction `newDir`. However, the `determineCycleDirection` 
function is not perfect, so this resulted:

```
const currentDir = vecImage.front.save.determineCycleDirection;
final switch(currentDir.kind)
{	case DetectedCycleDir.Kind.indifferent:
	{	turnNeeded = 0;
		break;
	}
			
	case DetectedCycleDir.Kind.selfCrossed:
	{	auto errRes = 
Message.directionSearchSelfcross(fileName).only.array;
		return WaypointsOrError.errors(errRes);
	}
			
	case DetectedCycleDir.Kind.timeout:
	{	auto errRes = 
Message.directionSearchTimeout(fileName).only.array;
		return WaypointsOrError.errors(errRes);
	}
			
	case DetectedCycleDir.Kind.known:
	{	turnNeeded = currentDir.knownValue == newDir? 0: 1;
		break;
	}
}
```

DetectedCycleDir definition (comments translated to English from 
the project):

```
union _DetectedCycleDir
{	import taggedalgebraic.taggedunion : Void;
	Void timeout; //exection broken, as it seemed to end up in 
infinite loop
	Void selfCrossed; //The shape outline crossed itself
	Void indifferent; //The direction is meaningless (0 - 2 points)
	CycleDirection known;
}
alias DetectedCycleDir = 
from!"taggedalgebraic".TaggedUnion!_DetectedCycleDir;
```


More information about the Digitalmars-d mailing list