-
Notifications
You must be signed in to change notification settings - Fork 0
/
arithmetics.c
73 lines (59 loc) · 1.16 KB
/
arithmetics.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
64
65
66
67
68
69
70
71
72
#include "lval.h"
#include "lenv.h"
#include "expressions.h"
#include "arithmetics.h"
#include <string.h>
lval* builtin_op(__attribute((unused)) lenv* e, lval* a, char* op)
{
// ensure every argument is a number
for (int i = 0; i < a->count; i++)
{
if (a->cell[i]->type != LVAL_NUM)
{
lval_del(a);
return lval_err("Cannot operate on non-number!");
}
}
lval* x = lval_pop(a, 0);
// negation
if ((strcmp(op, "-") == 0) && a->count == 0)
{
x->num = -x->num;
}
while(a->count > 0)
{
lval* y = lval_pop(a, 0);
if (strcmp(op, "+") == 0) { x->num += y->num; }
if (strcmp(op, "-") == 0) { x->num -= y->num; }
if (strcmp(op, "*") == 0) { x->num *= y->num; }
if (strcmp(op, "/") == 0) {
if (y->num == 0)
{
lval_del(x);
lval_del(y);
x = lval_err("Division by zero!");
break;
}
x->num /= y->num;
}
lval_del(y);
}
lval_del(a);
return x;
}
lval* builtin_add(lenv* e, lval*a)
{
return builtin_op(e, a, "+");
}
lval* builtin_sub(lenv* e, lval*a)
{
return builtin_op(e, a, "-");
}
lval* builtin_mul(lenv* e, lval*a)
{
return builtin_op(e, a, "*");
}
lval* builtin_div(lenv* e, lval*a)
{
return builtin_op(e, a, "/");
}