-
Notifications
You must be signed in to change notification settings - Fork 1
/
Unification.cs
106 lines (99 loc) · 3.53 KB
/
Unification.cs
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Sawmill;
namespace Amateurlog
{
class UnificationError : Exception
{
public UnificationError(string message) : base(message)
{
}
}
interface IUnifiable<T> : IRewritable<T> where T : IUnifiable<T>
{
string? AsVariable();
bool Match(T right);
}
static class Unifier
{
public static ImmutableHashSet<string> Variables<T>(this T value) where T : IUnifiable<T>
=> value
.SelfAndDescendants()
.Select(x => x.AsVariable())
.Where(name => name != null)
.Distinct()
.ToImmutableHashSet()!;
public static T Apply<T>(this ImmutableDictionary<string, T> subst, T value) where T : IUnifiable<T>
=> value.Rewrite(
x =>
{
var name = x.AsVariable();
if (name != null)
{
return subst.GetValueOrDefault(name, x);
}
return x;
}
);
public static ImmutableDictionary<string, T> Unify<T>(this T left, T right) where T : IUnifiable<T>
{
var leftName = left.AsVariable();
if (leftName != null)
{
return Bind(leftName, right);
}
var rightName = right.AsVariable();
if (rightName != null)
{
return Bind(rightName, left);
}
if (!left.Match(right))
{
throw new UnificationError("values didn't match");
}
var leftChildren = left.GetChildren().ToImmutableArray();
var rightChildren = right.GetChildren().ToImmutableArray();
return Solve(leftChildren, rightChildren);
}
public static ImmutableDictionary<string, T> Solve<T>(ImmutableArray<T> left, ImmutableArray<T> right) where T : IUnifiable<T>
{
if (left.Length != right.Length)
{
throw new UnificationError("values didn't match");
}
var subst = ImmutableDictionary<string, T>.Empty;
foreach (var (l, r) in left.Zip(right))
{
var newL = subst.Apply(l);
var newR = subst.Apply(r);
var newSubst = newL.Unify(newR);
subst = subst.Compose(newSubst);
}
return subst;
}
private static ImmutableDictionary<string, T> Bind<T>(string name, T value) where T : IUnifiable<T>
{
var valueName = value.AsVariable();
if (valueName != null && name == valueName)
{
return ImmutableDictionary<string, T>.Empty;
}
if (value.Variables().Contains(name))
{
throw new UnificationError("occurs check");
}
return ImmutableDictionary<string, T>.Empty.Add(name, value);
}
public static ImmutableDictionary<string, T> Compose<T>(
this ImmutableDictionary<string, T> left,
ImmutableDictionary<string, T> right
) where T : IUnifiable<T>
=> left
.Select(kvp => KeyValuePair.Create(kvp.Key, right.Apply(kvp.Value)))
.Where(kvp => !(kvp.Value is Variable v && v.Name == kvp.Key))
.Concat(right)
.ToImmutableDictionary();
}
}