-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEither.h
75 lines (63 loc) · 1.79 KB
/
Either.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2018 Sascha Grunert
#ifndef INCLUDE_EITHER_H_
#define INCLUDE_EITHER_H_
#include "Func.h"
/**
* @brief The 'Either' type declaration
*/
#define Either(a, b) either_##a##_##b##_type
/**
* @brief The 'Left' type declaration
*/
#define Left(a, b, d) \
(Either(a, b)) { \
.left = 1, .leftData = d, .rightData = null(b) \
}
/**
* @brief The 'Right' type declaration
*/
#define Right(a, b, d) \
(Either(a, b)) { \
.left = 0, .leftData = null(a), .rightData = d \
}
/**
* @brief Creates a new 'Either' type
*/
#define EITHER_TYPE(a, b) \
typedef struct { \
int left; \
a leftData; \
b rightData; \
} Either(a, b); \
Either(a, b) Left_##a##_##b(a v); \
Either(a, b) Left_##a##_##b(a v) { \
return Left(a, b, v); \
} \
Either(a, b) Right_##a##_##b(b v); \
Either(a, b) Right_##a##_##b(b v) { \
return Right(a, b, v); \
}
/**
* @brief Creates a new named 'Either'
*/
#define EITHER(a, b, c, d) \
typedef a b; \
typedef c d; \
EITHER_TYPE(b, d)
/**
* @brief Check if the Either contains Left data
*/
#define isLeft(o) ((o).left)
/**
* @brief Check if the Either contains Right data
*/
#define isRight(o) (!isLeft(o))
/**
* @brief Retrieve the Left data if possible
*/
#define fromLeft(x, o) (isLeft(o) ? o.leftData : x)
/**
* @brief Retrieve the Right data if possible
*/
#define fromRight(x, o) (isRight(o) ? o.rightData : x)
#endif // INCLUDE_EITHER_H_