Comparing slices with std.variant.Algebraic
Paul Backus
snarwin at gmail.com
Mon Sep 5 14:00:01 UTC 2022
On Monday, 5 September 2022 at 08:58:21 UTC, anonymouse wrote:
> On a related note, std.variant.Algebraic has been deprecated
> and the suggested replacement is std.sumtype.SumType. What is
> the proper way to make this conversion? Attempting to do a
> drop-in replacement results in the following errors:
>
> ```
> axis.d(400): Error: incompatible types for array comparison:
> `SumType!(bool, int, long, float, double, string, DateTime)[]`
> and `double[]`
> axis.d(86): Error: incompatible types for `(this.data[i]) +
> (rhs.data[i])`: both operands are of type `SumType!(bool, int,
> long, float, double, string, DateTime)`
> axis.d(414): Error: template instance ```
`SumType` does not attempt to forward operators to the contained
value like `Algebraic` does, so you will have to use
[`tryMatch`][1] to access the value(s) in cases like these.
```d
// Compare a DataType[] to a double[]
import std.algorithm.comparison: equal;
/+
Will throw an exception if lhs contains a value that can't
be compared to a double.
+/
alias cmp = (DataType lhs, double rhs) => lhs.tryMatch!(value =>
value == rhs);
DataType[] a;
double[] b;
bool result = a.equal!cmp(b);
```
```d
// Add two DataType values
/+
addValues will take two DataTypes as arguments and match on
both simultaneously.
If the two DataTypes do not contain values that can be added
together, an exception will be thrown.
See:
- https://dlang.org/phobos/std_sumtype.html#multiple-dispatch
-
https://dlang.org/phobos/std_sumtype.html#introspection-based-matching
+/
alias addValues = tryMatch!((lhs, rhs) => lhs + rhs);
DataType a;
DataType b;
DataType result = addValue(a, b);
```
[1]: https://phobos.dpldocs.info/std.sumtype.tryMatch.html
More information about the Digitalmars-d-learn
mailing list