turn one example into a test + fix bug in type variable substition function

This commit is contained in:
Joeri Exelmans 2025-05-08 17:30:42 +02:00
parent a664ddac8a
commit 35d682429b
4 changed files with 148 additions and 102 deletions

136
tests/recursive_types.js Normal file
View file

@ -0,0 +1,136 @@
import assert from "node:assert";
import { compareTypes } from "../lib/compare/type.js";
import { makeGeneric, substitute, unify } from "../lib/generics/generics.js";
import { Double, Int, Unit } from "../lib/primitives/primitive_types.js";
import { UNBOUND_SYMBOLS } from "../lib/primitives/typevars.js";
import { fnType, lsType, prodType, sumType, setType } from "../lib/structures/type_constructors.js";
import { prettyT } from "../lib/util/pretty.js";
// some recursive types:
const listOfSetOfSelf = lsType(self => setType(_ => self));
const makeLinkedList = elementType =>
sumType
(self => prodType
(_ => elementType)
(_ => self))
(_ => Unit);
const linkedListOfInt = makeLinkedList(Int);
const linkedListOfDouble = makeLinkedList(Double);
// some generic types
const genericFunction = makeGeneric((a,b) => fnType(_ => a)(_ => b));
const genericLinkedList = makeGeneric(a => makeLinkedList(a));
// pretty-printing of recursive types:
assert.equal(
prettyT(listOfSetOfSelf),
"#0[{#0}]",
);
assert.equal(
prettyT(linkedListOfInt),
"#0((Int #0) + Unit)",
);
assert.equal(
prettyT(genericFunction),
"(a -> b)",
);
assert.equal(
prettyT(genericLinkedList),
"#0((a #0) + Unit)",
);
// comparison
assert.equal(
compareTypes(listOfSetOfSelf)(listOfSetOfSelf),
0,
"types should be equal",
);
assert.equal(
compareTypes(linkedListOfInt)(linkedListOfInt),
0,
"types should be equal",
);
assert.notEqual(
compareTypes(linkedListOfInt)(linkedListOfDouble),
0,
"types should not be equal",
);
assert.equal(
compareTypes(linkedListOfDouble)(linkedListOfInt)
+ compareTypes(linkedListOfInt)(linkedListOfDouble),
0,
"comparison invariant",
);
assert.equal(
compareTypes(linkedListOfDouble)(linkedListOfDouble),
0,
"types should be equal",
)
assert.notEqual(
compareTypes(linkedListOfDouble)(listOfSetOfSelf),
0,
"types should not be equal",
);
assert.equal(
compareTypes(linkedListOfDouble)(listOfSetOfSelf)
+ compareTypes(listOfSetOfSelf)(linkedListOfDouble),
0,
"comparison invariant",
);
const genericList = makeGeneric(a => lsType(_ => a));
// substitution of type parameters
assert.equal(
// actual
prettyT(substitute(
genericLinkedList,
new Map([
[UNBOUND_SYMBOLS[0], Int],
])
)),
// expected
"#0((Int #0) + Unit)",
);
// unification (recursive)
assert.equal(
// actual
prettyT(unify(
genericLinkedList,
makeGeneric(() => linkedListOfInt)
)),
// expected
"#0((Int #0) + Unit)",
)
assert.equal(
// actual
prettyT(unify(
makeGeneric(() => listOfSetOfSelf),
genericList,
)),
// expected
"#0[{#0}]",
)