-
Notifications
You must be signed in to change notification settings - Fork 2
/
Maybe.h
70 lines (59 loc) · 1.49 KB
/
Maybe.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
// Copyright 2018 Sascha Grunert
#ifndef INCLUDE_MAYBE_H_
#define INCLUDE_MAYBE_H_
#include "Func.h"
/**
* @brief The 'Maybe' type declaration
*/
#define Maybe(t) maybe_##t##_type
/**
* @brief The 'Just' type declaration
*/
#define Just(t, d) \
(Maybe(t)) { \
.just = 1, .data = d \
}
/**
* @brief The 'Nothing' type declaration
*/
#define Nothing(t) \
(Maybe(t)) { \
.just = 0, .data = null(t) \
}
/**
* @brief Creates a new 'Maybe' type
*/
#define MAYBE_TYPE(t) \
typedef struct { \
int just; \
t data; \
} Maybe(t); \
Maybe(t) Just_##t(t val); \
Maybe(t) Just_##t(t val) { \
return Just(t, val); \
} \
Maybe(t) Nothing_##t(void); \
Maybe(t) Nothing_##t(void) { \
return Nothing(t); \
}
/**
* @brief Creates a new named 'Maybe'
*/
#define MAYBE(t, n) \
typedef t n; \
MAYBE_TYPE(n)
/**
* @brief Check if the Maybe contains any data
*/
#define isJust(o) ((o).just)
/**
* @brief Check if the Maybe contains nothing
*/
#define isNothing(o) (!isJust(o))
/**
* @brief Takes a default value and a Maybe value. If the Maybe is Nothing,
* it returns the default values; otherwise, it returns the value
* contained in the Maybe.
*/
#define fromMaybe(x, o) (isJust(o) ? o.data : x)
#endif // INCLUDE_MAYBE_H_