-
Notifications
You must be signed in to change notification settings - Fork 2
/
list_iterable.c
63 lines (55 loc) · 1.37 KB
/
list_iterable.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
#include "list_iterable.h"
#include "func_iter.h"
#include <stdlib.h>
/* Create IntNode from given value */
static IntNode* create_intnode(int val)
{
IntNode* node = malloc(sizeof(*node));
if (node == NULL) {
return NULL;
}
node->val = val;
node->next = NULL;
return node;
}
IntList prepend_intnode(int val, IntList list)
{
IntNode* node = create_intnode(val);
if (node == NULL) {
fprintf(stderr, "OOM in prepend_intnode");
exit(1);
}
node->next = list;
return node;
}
void print_intlist(IntNode const* head)
{
while (head != Nil) {
printf("%d ", head->val);
head = head->next;
}
puts("");
}
IntList free_intlist(IntNode* head)
{
IntList tmp = Nil;
while (head != Nil) {
tmp = head;
head = head->next;
free(tmp);
}
return Nil;
}
/* `next` implementation for `ListIter(ConstIntList)` */
static Maybe(int) intlistnxt(ListIter(ConstIntList) * self)
{
IntNode const* node = self->curr;
if (node == Nil) {
return Nothing(int);
}
/* Progress the stored list pointer */
self->curr = node->next;
return Just(node->val, int);
}
/* Implement `Iterator` for `ListIter(ConstIntList) *`, which in turn is for a singular linked list of ints */
impl_iterator(ListIter(ConstIntList) *, int, prep_listiter_of(ConstIntList), intlistnxt)