about summary refs log tree commit diff
path: root/usth/ICT2.1/labwork/2/construct.c
blob: db32d8abb86c36a49cb4483c6c3b301238ad696a (plain) (blame)
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
/*
 * Lisp construct implementation.
 * This is free and unencumbered software released into the public domain.
 */

#include <stdlib.h>

#include "construct.h"

construct *cons(void *first, construct *rest)
{
	construct *list = malloc(sizeof(construct));
	list->car = first;
	list->cdr = rest;
	return list;
}

void *car(construct *list)
{
	return list->car;
}

construct *cdr(construct *list)
{
	return list->cdr;
}

size_t length(construct *list)
{
	if (list == NULL)
		return 0;
	return length(cdr(list)) + 1;
}

void *nth(construct *list, size_t n)
{
	if (list == NULL)
		return NULL;
	return n ? nth(cdr(list), n - 1) : car(list);
}

/*
 * Try to insert x before item of index i and return the new construct.
 * Return NULL on invalid index.
 */
construct *insert(void *x, construct *list, size_t i)
{
	if (!i)
		return cons(x, list);
	if (list == NULL)
		return NULL;

	void *first = car(list);
	construct *rest = cdr(list);
	free(list);
	return cons(first, insert(x, rest, i - 1));
}