dope2/structures/sum.js
2025-03-24 17:28:07 +01:00

57 lines
1.3 KiB
JavaScript

import { prodType } from "./types.js";
import { Type } from "../primitives/types.js";
import { typedFnType } from "./types.js";
import { makeGeneric } from "../generics/generics.js";
import { sumType } from "./types.js";
export const constructorLeft = left => ({variant: "L", value: left });
export const constructorRight = right => ({variant: "R", value: right});
// signature:
// sum-type -> (leftType -> resultType, rightType -> resultType) -> resultType
export const match = sum => handlers => sum.variant === "L"
? handlers.left(sum.value)
: handlers.right(sum.value);
export const ModuleSum = {l:[
// binary type constructor
// Type -> Type -> Type
...typedFnType(sumType, fnType =>
fnType
(Type)
(fnType
(Type)
(Type)
),
),
// a -> a | b
...typedFnType(constructorLeft, fnType =>
makeGeneric((a, b) =>
fnType
(a)
(sumType(a)(b))
)),
// b -> a | b
...typedFnType(constructorRight, fnType =>
makeGeneric((a, b) =>
fnType
(b)
(sumType(a)(b))
)),
// a | b -> (a -> c, b-> c) -> c
...typedFnType(match, fnType =>
makeGeneric((a, b, c) =>
fnType
(sumType(a)(b))
(fnType
(prodType
(fnType(a)(c))
(fnType(b)(c))
)
(c)
)
)),
]};