-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumber.c
84 lines (71 loc) · 1.91 KB
/
number.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
73
74
75
76
77
78
79
80
81
82
83
84
#include "lilscheme.h"
// Integers
// TODO: integrate small integers into handles to save space
Handle CreateInteger(int value) {
Handle hnd = CreateObject(TYPE_INT,0);
DATA_DEREF(int,hnd) = value;
return hnd;
}
int UnboxInteger(Handle hnd) {
if (DEREF(hnd)->type != TYPE_INT) {
panic("can't UnboxInteger that type");
}
return DATA_DEREF(int,hnd);
}
// Floating-point
Handle CreateFloat(double value) {
Handle hnd = CreateObject(TYPE_FLOAT,0);
DATA_DEREF(double,hnd) = value;
return hnd;
}
double UnboxFloat(Handle hnd) {
if (DEREF(hnd)->type != TYPE_FLOAT) {
panic("can't UnboxFloat that type");
}
return DATA_DEREF(double,hnd);
}
// Coercive unboxing
int CoerceToInt(Handle n) {
OBJTYPE t = TYPEOF(n);
if (t == TYPE_INT) return UnboxInteger(n);
else if (t == TYPE_FLOAT) return (int)UnboxFloat(n);
else panic("can't CoerceToInteger that type");
}
double CoerceToDouble(Handle n) {
OBJTYPE t = TYPEOF(n);
if (t == TYPE_FLOAT) return UnboxFloat(n);
else if (t == TYPE_INT) return (double)UnboxInteger(n);
else panic("can't CoerceToDouble that type");
}
// Numericity
int IsNumericType(OBJTYPE t) {
return t == TYPE_INT || t == TYPE_FLOAT;
}
int IsNumeric(Handle o) {
return IsNumericType(TYPEOF(o));
}
// Comparisons
// returns a positive number if a > b
// a negative number if a < b
// zero if a = b
int CompareNumbers(Handle a, Handle b) {
TypecheckNumeric(a);
TypecheckNumeric(b);
OBJTYPE ta = TYPEOF(a);
OBJTYPE tb = TYPEOF(b);
if (ta == TYPE_FLOAT || tb == TYPE_FLOAT) {
// compare as floating point
double da = CoerceToDouble(a);
double db = CoerceToDouble(b);
if (da > db) return 1;
else if (da < db) return -1;
else return 0;
}
else {
int ia = UnboxInteger(a);
int ib = UnboxInteger(b);
if (ia > ib) return 1;
else if (ia < ib) return -1;
else return 0;
}
}