-
Notifications
You must be signed in to change notification settings - Fork 20
/
functional.c
60 lines (53 loc) · 1.15 KB
/
functional.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
#include <stdlib.h>
#include <stdio.h>
#include "list.h"
#include "functional.h"
#include "closure.h"
//some standard functional programming functions
void
iter(list *l, void (*fn)(void *, void *), void *args) {
list *curr;
for (curr = l; curr != NULL; curr = curr->next) {
(*fn)(curr->val, args);
}
}
list *
map(list *l, void *(*fn)(void *, void *), void *args) {
list *o = NULL;
list *curr;
for (curr = l; curr != NULL; curr = curr->next) {
o = append(o, (*fn)(curr->val, args));
}
return o;
}
list *
lmap(list *l, closure *cl) {
list *o = NULL;
list *curr;
for (curr = l; curr != NULL; curr = curr->next) {
o = append(o, call(cl, (envobj *)curr->val));
}
return o;
}
list *
filter(list *l, bool (*fn)(void *, void *), void *args) {
list *o = NULL;
list *curr;
for (curr = l; curr != NULL; curr = curr->next) {
if ((*fn)(curr->val, args)) {
o = append(o, copyitem(curr->val));
}
}
return o;
}
//not lazy
list *
range(int start, int end) {
list *o = NULL;
for (int i = start; i <= end; ++i) {
int *aloc = malloc(sizeof(int));
*aloc = i;
o = append(o, (void *)aloc);
}
return o;
}