can auto-generate comparison functions for composed types

This commit is contained in:
Joeri Exelmans 2025-04-17 16:43:28 +02:00
parent 0b262daf7f
commit 4d1fb81492
6 changed files with 72 additions and 35 deletions

View file

@ -1,3 +1,4 @@
import { makeCompareFn } from "../compare/registry.js";
import { Bottom, Int, Unit } from "../primitives/types.js";
import { unit } from "../primitives/unit.js";
import { capitalizeFirstLetter } from "../util/util.js";
@ -66,23 +67,36 @@ const variants = [
constructorProduct("not_found")(Unit),
];
const myEnum = enumType(variants);
const myEnumType = enumType(variants);
console.log(prettyT(myEnum));
console.log("observe the type that was generated:");
console.log(prettyT(myEnumType));
const [newPrice, newPrices, newNotFound] = makeConstructors(variants);
console.log(newPrice(10));
console.log(newPrices([20,30]));
console.log(newNotFound(unit));
const price = newPrice(10);
const prices = newPrices({l:[20,30]});
const notFound = newNotFound(unit);
const myMatchFn = makeMatchFn(variants);
console.log("observe the encoding of different variant instances:");
console.log(price);
console.log(prices);
console.log(notFound);
const matchVariant = x => myMatchFn(x)
const myEnumToString = x => makeMatchFn(variants)(x)
(price => `Price: ${price}`)
(prices => `Prices: ${prices}`)
(prices => `Prices: ${prices.l}`)
(() => "Not found!");
console.log(matchVariant(newPrice(10)));
console.log(matchVariant(newPrices([20,30])));
console.log(matchVariant(newNotFound(unit)));
console.log("observe the generated match function in action:")
console.log(myEnumToString(price));
console.log(myEnumToString(prices));
console.log(myEnumToString(notFound));
const compareMyEnum = makeCompareFn(myEnumType);
console.log(compareMyEnum(price)(prices)); // smaller
console.log(compareMyEnum(prices)(price)); // bigger
console.log(compareMyEnum(notFound)(price)); // bigger
console.log(compareMyEnum(prices)(prices)); // equal
console.log(compareMyEnum(newPrice(5))(newPrice(6))); // smaller