]> git.lizzy.rs Git - nothing.git/blob - src/script/builtins.c
Introduce length_of_list
[nothing.git] / src / script / builtins.c
1 #include <assert.h>
2 #include <math.h>
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 #include "builtins.h"
8
9 static bool equal_atoms(struct Atom *atom1, struct Atom *atom2)
10 {
11     assert(atom1);
12     assert(atom2);
13
14     if (atom1->type != atom2->type) {
15         return false;
16     }
17
18     switch (atom1->type) {
19     case ATOM_SYMBOL:
20         return strcmp(atom1->sym, atom2->sym) == 0;
21
22     case ATOM_NUMBER:
23         return atom1->num == atom2->num;
24
25     case ATOM_STRING:
26         return strcmp(atom1->str, atom2->str) == 0;
27     }
28
29     return false;
30 }
31
32 static bool equal_cons(struct Cons *cons1, struct Cons *cons2)
33 {
34     assert(cons1);
35     assert(cons2);
36     return equal(cons1->car, cons2->car) && equal(cons1->cdr, cons2->cdr);
37 }
38
39 bool equal(struct Expr obj1, struct Expr obj2)
40 {
41     if (obj1.type != obj2.type) {
42         return false;
43     }
44
45     switch (obj1.type) {
46     case EXPR_ATOM:
47         return equal_atoms(obj1.atom, obj2.atom);
48
49     case EXPR_CONS:
50         return equal_cons(obj1.cons, obj2.cons);
51
52     case EXPR_VOID:
53         return true;
54     }
55
56     return true;
57 }
58
59 bool nil_p(struct Expr obj)
60 {
61     return symbol_p(obj)
62         && strcmp(obj.atom->sym, "nil") == 0;
63 }
64
65 bool symbol_p(struct Expr obj)
66 {
67     return obj.type == EXPR_ATOM
68         && obj.atom->type == ATOM_SYMBOL;
69 }
70
71 bool cons_p(struct Expr obj)
72 {
73     return obj.type == EXPR_CONS;
74 }
75
76 bool list_p(struct Expr obj)
77 {
78     if (nil_p(obj)) {
79         return true;
80     }
81
82     if (obj.type == EXPR_CONS) {
83         return list_p(obj.cons->cdr);
84     }
85
86     return false;
87 }
88
89 long int length_of_list(struct Expr obj)
90 {
91     long int count = 0;
92
93     while (!nil_p(obj)) {
94         count++;
95         obj = obj.cons->cdr;
96     }
97
98     return count;
99 }
100
101 struct Expr assoc(struct Expr key, struct Expr alist)
102 {
103     while (cons_p(alist)) {
104         if (cons_p(alist.cons->car) && equal(alist.cons->car.cons->car, key)) {
105             return alist.cons->car;
106         }
107
108         alist = alist.cons->cdr;
109     }
110
111     return alist;
112 }
113
114 static struct Expr list_rec(Gc *gc, size_t n, va_list args)
115 {
116     if (n == 0) {
117         return NIL(gc);
118     }
119
120     struct Expr obj = va_arg(args, struct Expr);
121     return CONS(gc, obj, list_rec(gc, n - 1, args));
122 }
123
124 struct Expr list(Gc *gc, size_t n, ...)
125 {
126     va_list args;
127     va_start(args, n);
128     struct Expr obj = list_rec(gc, n, args);
129     va_end(args);
130     return obj;
131 }