/
name-constrained.c
90 lines (77 loc) · 2.98 KB
/
name-constrained.c
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CONCAT_(x, y) x ## y
#define CONCAT(x, y) CONCAT_(x, y)
/* Consistently name the impl functions */
#define ImplName(T, TypeclassName) CONCAT(CONCAT(T, _to_), CONCAT(TypeclassName, _inst))
/* "Apply" a typeclass over a concrete type */
#define ap(x, T, TypeclassName) ImplName(T, TypeclassName)(x)
/* The `Show` typeclass allows types to be turned into their string representation */
typedef struct
{
char* (*const show)(void* self);
} ShowTC;
typedef struct
{
void* self;
ShowTC const* tc;
} Show;
#define impl_show(T, show_f) \
static inline char* CONCAT(show_f, __)(void* self) \
{ \
char* (*const show_)(T* self) = (show_f); \
(void)show_; \
return show_f(self); \
} \
Show ImplName(T, Show)(T* x) \
{ \
static ShowTC const tc = { .show = (CONCAT(show_f, __)) }; \
return (Show){ .tc = &tc, .self = x }; \
}
/* Polymorphic printing function */
void print(Show showable)
{
char* s = showable.tc->show(showable.self);
puts(s);
free(s);
}
/* A very holy enum */
typedef enum
{
holy,
hand,
grenade
} Antioch;
static inline char* strdup_(char const* x)
{
char* s = malloc((strlen(x) + 1) * sizeof(*s));
strcpy(s, x);
return s;
}
/* The `show` function implementation for `Antioch*` */
static char* antioch_show(Antioch* x)
{
/*
Note: The `show` function of a `Show` typeclass is expected to return a malloc'ed value
The users of a generic `Show` are expected to `free` the returned pointer from the function `show`.
*/
switch (*x)
{
case holy:
return strdup_("holy");
case hand:
return strdup_("hand");
case grenade:
return strdup_("grenade");
default:
return strdup_("breakfast cereal");
}
}
/* Make function to build a generic `Show` out of a concrete type- `Antioch` */
impl_show(Antioch, antioch_show)
int main(void)
{
print(ap(&(Antioch){ holy }, Antioch, Show));
return 0;
}