-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
62 lines (52 loc) · 1.02 KB
/
main.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
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE {
int value;
struct NODE *next;
} Node;
typedef Node* (f1)(Node*);
typedef Node* (f2)(Node*, Node*);
Node *cons(int value, Node *node) {
Node *newNode = malloc(sizeof(Node));
newNode->next = node;
newNode->value = value;
return newNode;
}
Node *reduce(f2 *f, Node *init, Node *coll) {
return coll
? reduce(f, f(init, coll), coll->next)
: init;
}
Node *map(f1 *f, Node *x) {
if (x) {
Node *y = f(x);
y->next = map(f, x->next);
return y;
} else {
return x;
}
}
void show(Node *node) {
printf("(");
while (node){
printf(node->next ? "%d, " : "%d", node->value);
node = node->next;
};
printf(")\n");
}
Node *add(Node *x, Node *y) {
return cons(x->value + y->value, NULL);
}
Node *inc(Node *x) {
return add(x, cons(1, NULL));
}
int main () {
printf("ok\n");
Node *x = cons(2, cons(1, NULL));
Node *y = map(inc, x);
Node *z = reduce(add, cons(0, NULL), y);
show(x);
show(y);
show(z);
return 0;
}