Debian Codegraph @

libphobos/testsuite/libphobos.phobos/std_sumtype.d

raw
1 @safe unittest
2 {
3 import std.sumtype;
4
5 import std.math.operations : isClose;
6
7 struct Fahrenheit { double degrees; }
8 struct Celsius { double degrees; }
9 struct Kelvin { double degrees; }
10
11 alias Temperature = SumType!(Fahrenheit, Celsius, Kelvin);
12
13 // Construct from any of the member types.
14 Temperature t1 = Fahrenheit(98.6);
15 Temperature t2 = Celsius(100);
16 Temperature t3 = Kelvin(273);
17
18 // Use pattern matching to access the value.
19 Fahrenheit toFahrenheit(Temperature t)
20 {
21 return Fahrenheit(
22 t.match!(
23 (Fahrenheit f) => f.degrees,
24 (Celsius c) => c.degrees * 9.0/5 + 32,
25 (Kelvin k) => k.degrees * 9.0/5 - 459.4
26 )
27 );
28 }
29
30 assert(toFahrenheit(t1).degrees.isClose(98.6));
31 assert(toFahrenheit(t2).degrees.isClose(212));
32 assert(toFahrenheit(t3).degrees.isClose(32));
33
34 // Use ref to modify the value in place.
35 void freeze(ref Temperature t)
36 {
37 t.match!(
38 (ref Fahrenheit f) => f.degrees = 32,
39 (ref Celsius c) => c.degrees = 0,
40 (ref Kelvin k) => k.degrees = 273
41 );
42 }
43
44 freeze(t1);
45 assert(toFahrenheit(t1).degrees.isClose(32));
46
47 // Use a catch-all handler to give a default result.
48 bool isFahrenheit(Temperature t)
49 {
50 return t.match!(
51 (Fahrenheit f) => true,
52 _ => false
53 );
54 }
55
56 assert(isFahrenheit(t1));
57 assert(!isFahrenheit(t2));
58 assert(!isFahrenheit(t3));
59 }
60
61 @safe unittest
62 {
63 import std.sumtype;
64
65 alias ExampleSumType = SumType!(int, string, double);
66
67 ExampleSumType a = 123;
68 ExampleSumType b = "hello";
69 ExampleSumType c = 3.14;
70
71 assert(a.handle == "got an int");
72 assert(b.handle == "got a string");
73 assert(c.handle == "got a double");
74 }
75
76 @system unittest
77 {
78 import std.sumtype;
79
80 import std.functional : partial;
81 import std.traits : EnumMembers;
82 import std.typecons : Tuple;
83
84 enum Op : string
85 {
86 Plus = "+",
87 Minus = "-",
88 Times = "*",
89 Div = "/"
90 }
91
92 // An expression is either
93 // - a number,
94 // - a variable, or
95 // - a binary operation combining two sub-expressions.
96 alias Expr = SumType!(
97 double,
98 string,
99 Tuple!(Op, "op", This*, "lhs", This*, "rhs")
100 );
101
102 // Shorthand for Tuple!(Op, "op", Expr*, "lhs", Expr*, "rhs"),
103 // the Tuple type above with Expr substituted for This.
104 alias BinOp = Expr.Types[2];
105
106 // Factory function for number expressions
107 Expr* num(double value)
108 {
109 return new Expr(value);
110 }
111
112 // Factory function for variable expressions
113 Expr* var(string name)
114 {
115 return new Expr(name);
116 }
117
118 // Factory function for binary operation expressions
119 Expr* binOp(Op op, Expr* lhs, Expr* rhs)
120 {
121 return new Expr(BinOp(op, lhs, rhs));
122 }
123
124 // Convenience wrappers for creating BinOp expressions
125 alias sum = partial!(binOp, Op.Plus);
126 alias diff = partial!(binOp, Op.Minus);
127 alias prod = partial!(binOp, Op.Times);
128 alias quot = partial!(binOp, Op.Div);
129
130 // Evaluate expr, looking up variables in env
131 double eval(Expr expr, double[string] env)
132 {
133 return expr.match!(
134 (double num) => num,
135 (string var) => env[var],
136 (BinOp bop)
137 {
138 double lhs = eval(*bop.lhs, env);
139 double rhs = eval(*bop.rhs, env);
140 final switch (bop.op)
141 {
142 static foreach (op; EnumMembers!Op)
143 {
144 case op:
145 return mixin("lhs" ~ op ~ "rhs");
146 }
147 }
148 }
149 );
150 }
151
152 // Return a "pretty-printed" representation of expr
153 string pprint(Expr expr)
154 {
155 import std.format : format;
156
157 return expr.match!(
158 (double num) => "%g".format(num),
159 (string var) => var,
160 (BinOp bop) => "(%s %s %s)".format(
161 pprint(*bop.lhs),
162 cast(string) bop.op,
163 pprint(*bop.rhs)
164 )
165 );
166 }
167
168 Expr* myExpr = sum(var("a"), prod(num(2), var("b")));
169 double[string] myEnv = ["a":3, "b":4, "c":7];
170
171 assert(eval(*myExpr, myEnv) == 11);
172 assert(pprint(*myExpr) == "(a + (2 * b))");
173 }
174
175 @safe unittest
176 {
177 import std.sumtype;
178
179 static struct ConvertsToSumType
180 {
181 SumType!int payload;
182 alias payload this;
183 }
184
185 static struct ContainsSumType
186 {
187 SumType!int payload;
188 }
189
190 assert(isSumType!(SumType!int));
191 assert(isSumType!ConvertsToSumType);
192 assert(!isSumType!ContainsSumType);
193 }
194
195 @safe unittest
196 {
197 import std.sumtype;
198
199 alias Number = SumType!(double, int);
200
201 Number x;
202
203 // Problem: because int implicitly converts to double, the double
204 // handler is used for both types, and the int handler never matches.
205 assert(!__traits(compiles,
206 x.match!(
207 (double d) => "got double",
208 (int n) => "got int"
209 )
210 ));
211
212 // Solution 1: put the handler for the "more specialized" type (in this
213 // case, int) before the handler for the type it converts to.
214 assert(__traits(compiles,
215 x.match!(
216 (int n) => "got int",
217 (double d) => "got double"
218 )
219 ));
220
221 // Solution 2: use a template that only accepts the exact type it's
222 // supposed to match, instead of any type that implicitly converts to it.
223 alias exactly(T, alias fun) = function (arg)
224 {
225 static assert(is(typeof(arg) == T));
226 return fun(arg);
227 };
228
229 // Now, even if we put the double handler first, it will only be used for
230 // doubles, not ints.
231 assert(__traits(compiles,
232 x.match!(
233 exactly!(double, d => "got double"),
234 exactly!(int, n => "got int")
235 )
236 ));
237 }
238
239 @safe unittest
240 {
241 import std.sumtype;
242
243 struct Point2D { double x, y; }
244 struct Point3D { double x, y, z; }
245
246 alias Point = SumType!(Point2D, Point3D);
247
248 version (none)
249 {
250 // This function works, but the code is ugly and repetitive.
251 // It uses three separate calls to match!
252 @safe pure nothrow @nogc
253 bool sameDimensions(Point p1, Point p2)
254 {
255 return p1.match!(
256 (Point2D _) => p2.match!(
257 (Point2D _) => true,
258 _ => false
259 ),
260 (Point3D _) => p2.match!(
261 (Point3D _) => true,
262 _ => false
263 )
264 );
265 }
266 }
267
268 // This version is much nicer.
269 @safe pure nothrow @nogc
270 bool sameDimensions(Point p1, Point p2)
271 {
272 alias doMatch = match!(
273 (Point2D _1, Point2D _2) => true,
274 (Point3D _1, Point3D _2) => true,
275 (_1, _2) => false
276 );
277
278 return doMatch(p1, p2);
279 }
280
281 Point a = Point2D(1, 2);
282 Point b = Point2D(3, 4);
283 Point c = Point3D(5, 6, 7);
284 Point d = Point3D(8, 9, 0);
285
286 assert( sameDimensions(a, b));
287 assert( sameDimensions(c, d));
288 assert(!sameDimensions(a, c));
289 assert(!sameDimensions(d, b));
290 }
291
292 @safe unittest
293 {
294 import std.sumtype;
295
296 alias handleInt = (int i) => "got an int";
297
298 assert( canMatch!(handleInt, int));
299 assert(!canMatch!(handleInt, string));
300 }
301
302 @safe unittest
303 {
304 import std.sumtype;
305
306 SumType!(string, double) example = "hello";
307
308 assert( example.has!string);
309 assert(!example.has!double);
310
311 // If T isn't part of the SumType, has!T will always return false.
312 assert(!example.has!int);
313 }
314
315 @safe unittest
316 {
317 import std.sumtype;
318
319 alias Example = SumType!(string, double);
320
321 Example m = "mutable";
322 const Example c = "const";
323 immutable Example i = "immutable";
324
325 assert( m.has!string);
326 assert(!m.has!(const(string)));
327 assert(!m.has!(immutable(string)));
328
329 assert(!c.has!string);
330 assert( c.has!(const(string)));
331 assert(!c.has!(immutable(string)));
332
333 assert(!i.has!string);
334 assert(!i.has!(const(string)));
335 assert( i.has!(immutable(string)));
336 }
337
338 @safe unittest
339 {
340 import std.sumtype;
341
342 import std.algorithm.iteration : filter;
343 import std.algorithm.comparison : equal;
344
345 alias Example = SumType!(string, double);
346
347 auto arr = [
348 Example("foo"),
349 Example(0),
350 Example("bar"),
351 Example(1),
352 Example(2),
353 Example("baz")
354 ];
355
356 auto strings = arr.filter!(has!string);
357 auto nums = arr.filter!(has!double);
358
359 assert(strings.equal([Example("foo"), Example("bar"), Example("baz")]));
360 assert(nums.equal([Example(0), Example(1), Example(2)]));
361 }
362
363 @safe unittest
364 {
365 import std.sumtype;
366
367 SumType!(string, double) example1 = "hello";
368 SumType!(string, double) example2 = 3.14;
369
370 assert(example1.get!string == "hello");
371 assert(example2.get!double == 3.14);
372 }
373
374 @safe unittest
375 {
376 import std.sumtype;
377
378 alias Example = SumType!(string, double);
379
380 Example m = "mutable";
381 const(Example) c = "const";
382 immutable(Example) i = "immutable";
383
384 assert(m.get!string == "mutable");
385 assert(c.get!(const(string)) == "const");
386 assert(i.get!(immutable(string)) == "immutable");
387 }
388
389 @safe unittest
390 {
391 import std.sumtype;
392
393 import std.algorithm.iteration : map;
394 import std.algorithm.comparison : equal;
395
396 alias Example = SumType!(string, double);
397
398 auto arr = [Example(0), Example(1), Example(2)];
399 auto values = arr.map!(get!double);
400
401 assert(values.equal([0, 1, 2]));
402 }
403
404 @safe unittest
405 {
406 import std.sumtype;
407
408 SumType!(string, double) example = "hello";
409
410 assert(example.tryGet!string == "hello");
411
412 double result = double.nan;
413 try
414 result = example.tryGet!double;
415 catch (MatchException e)
416 result = 0;
417
418 // Exception was thrown
419 assert(result == 0);
420 }
421
422 @safe unittest
423 {
424 import std.sumtype;
425
426 import std.exception : assertThrown;
427
428 const(SumType!(string, double)) example = "const";
429
430 // Qualifier mismatch; throws exception
431 assertThrown!MatchException(example.tryGet!string);
432 // Qualifier matches; no exception
433 assert(example.tryGet!(const(string)) == "const");
434 }
435
436 @safe unittest
437 {
438 import std.sumtype;
439
440 import std.algorithm.iteration : map, sum;
441 import std.functional : pipe;
442 import std.exception : assertThrown;
443
444 alias Example = SumType!(string, double);
445
446 auto arr1 = [Example(0), Example(1), Example(2)];
447 auto arr2 = [Example("foo"), Example("bar"), Example("baz")];
448
449 alias trySum = pipe!(map!(tryGet!double), sum);
450
451 assert(trySum(arr1) == 0 + 1 + 2);
452 assertThrown!MatchException(trySum(arr2));
453 }
454