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
|
// Copyright (c) 2023, Marvin Borner <dev@marvinborner.de>
// SPDX-License-Identifier: MIT
#include <stdio.h>
#include <term.h>
#include <reduce.h>
#include <log.h>
static struct term *substitute(struct term *term, struct term *substitution,
size_t level)
{
if (term->type == VAR && term->u.var.index == level) {
return substitution;
} else if (term->type == ABS) {
struct term *new =
substitute(term->u.abs.term, substitution, level + 1);
return term_rehash_abs(term, new);
} else if (term->type == APP) {
struct term *lhs =
substitute(term->u.app.lhs, substitution, level);
struct term *rhs =
substitute(term->u.app.rhs, substitution, level);
return term_rehash_app(term, lhs, rhs);
}
fatal("invalid type %d\n", term->type);
}
static struct term *reduce_app(struct term *term)
{
if (term->u.app.lhs->type == ABS) {
return substitute(term->u.app.lhs->u.abs.term, term->u.app.rhs,
0);
} else {
struct term *lhs = reduce(term->u.app.lhs);
struct term *rhs = reduce(term->u.app.rhs);
return term_rehash_app(term, lhs, rhs);
}
}
static struct term *reduce_abs(struct term *term)
{
return reduce(term->u.abs.term);
}
struct term *reduce(struct term *term)
{
if (term->type == APP) {
return reduce_app(term);
} else if (term->type == ABS) {
return reduce_abs(term);
} else if (term->type == VAR) {
return term;
}
fatal("invalid type %d\n", term->type);
}
|