Semantic Analysis
:material-circle-edit-outline: 约 153 个字 :fontawesome-solid-code: 40 行代码 :material-clock-time-two-outline: 预计阅读时间 1 分钟
Symbol Tables
Effective Imperative Symbol Tables
数据结构
我们需要让查询速度很快,自然就想到哈希表
我们称每一条链表为一个 bucket
struct bucket {
string key;
void *binding;
struct bucket *next;
};
#define SIZE 109
struct bucket *table[SIZE];
unsigned int hash(char *s0){
unsigned int h=0; char *s;
for(s=s0; *s; s++) h=h*65599 + *s;
return h;
}
struct bucket *Bucket (string key, void *binding, struct bucket *next) {
struct bucket *b=checked_malloc(sizeof(*b));
b->key = key;
b->binding = binding;
b->next = next;
return b;
}
hash
函数用于实现哈希值的计算:
插入
我们就插在链表的头,这样后插入的就在最上面,删除时会方便很多,因为后进的要先出
void insert(string key, void *binding) {
int index=hash(key)%SIZE;
table[index]=Bucket(key, binding, table[index]);
}
查询
void *lookup(string key) {
int index=hash(key)%SIZE;
struct bucket *b;
for (b = table[index]; b; b=b>next)
if (0==strcmp(b->key,key))
return b->binding;
return NULL;
}
删除
Efficient Functional Symbol Tables
略,思路和实验写的不一样,有复制数组(只复制指针,不复制链表)的,有二叉树的(需要复制路径上的所有结点)