/
c_without_closures.c
78 lines (64 loc) · 1.99 KB
/
c_without_closures.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
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
// The key point is that function are only code pointers
// rather than create structs for closures, which would work fine,
// we follow common C practice of having higher-order functions
// take explicit environment fields as another argument
// -- if they don't, then they are much less useful
// void* requires lots of unchecked conversions between types,
// but C has no notion of type variables
typedef struct List list_t;
struct List {
void* head;
list_t * tail;
};
list_t * makelist (void * x, list_t * xs) {
list_t * ans = (list_t *)malloc(sizeof(list_t));
ans -> head = x;
ans -> tail = xs;
return ans;
}
// as in the Java versions, we show simple recursive solutions because
// the loop-based ones require mutation and previous pointers.
// But the more important point is the explicit env field passed to the
// function pointer
list_t * map(void* (*f)(void*,void*), void* env, list_t * xs) {
if(xs == NULL)
return NULL;
return makelist(f(env,xs->head), map(f,env,xs-> tail));
}
list_t * filter(bool (*f)(void*,void*), void* env, list_t * xs) {
if(xs == NULL)
return NULL;
if(f(env,xs->head))
return makelist(xs->head, filter(f,env,xs->tail));
return filter(f,env,xs->tail);
}
int length(list_t* xs) {
int ans = 0;
while(xs != NULL) {
++ans;
xs = xs->tail;
}
return ans;
}
// clients of our list implementation:
// [the clients that cast from void* to intptr_t are technically not leagal
// C, as explained below if curious]
// awful type casts to match what map expects
void* doubleInt(void* ignore, void* i) {
return (void*)(((intptr_t)i)*2);
}
//assumes list holds intptr_t fields
list_t * doubleAll(list_t * xs) {
return map(doubleInt, NULL, xs);
}
// awful type casts to match what filter expects
bool isN(void* n, void* i) {
return ((intptr_t)n)==((intptr_t)i);
}
//assumes list hold intptr_t fields
int countNs(list_t * xs, intptr_t n) {
return length(filter(isN, (void*)n, xs));
}