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
85
86
|
// 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)
{
/* term_print(term); */
/* fprintf(stderr, " <- "); */
/* term_print(substitution); */
/* fprintf(stderr, " @ %ld\n", 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);
if (term->u.abs.term->hash == substitution->hash)
return term;
term_deref(term->u.abs.term);
struct term *rehashed = term_rehash_abs(term, new);
term_deref_head(term);
return rehashed;
} 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);
if (term->u.app.lhs->hash == substitution->hash &&
term->u.app.rhs->hash == substitution->hash)
return term;
if (term->u.app.lhs->hash != substitution->hash)
term_deref(term->u.app.lhs);
if (term->u.app.rhs->hash != substitution->hash)
term_deref(term->u.app.rhs);
struct term *rehashed = term_rehash_app(term, lhs, rhs);
term_deref_head(term);
return rehashed;
}
fatal("invalid type %d\n", term->type);
}
// APP: reduction of application
// ([X],Y) -> X/Y
// (X,Y) -> (RED(X),RED(Y))
static struct term *reduce_app(struct term *term)
{
if (term->u.app.lhs->type == ABS) {
struct term *new = substitute(term->u.app.lhs->u.abs.term,
term->u.app.rhs, -1);
term_deref_head(term);
return new;
} else {
struct term *lhs = reduce(term->u.app.lhs);
struct term *rhs = reduce(term->u.app.rhs);
return term_rehash_app(term, lhs, rhs);
}
}
// ABS: reduction of abstractions
// [X] -> [RED(X)]
static struct term *reduce_abs(struct term *term)
{
struct term *inner = reduce(term->u.abs.term);
return term_rehash_abs(term, inner);
}
// RED: main reduction
// (X,Y) -> APP((X,Y))
// [X] -> ABS([X])
// X -> X
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);
}
|