typocomath/src/Complex/type.ts

55 lines
1.5 KiB
TypeScript

import {
joinTypes, typeOfDependency, Dependency,
} from '../core/Dispatcher.js'
export type Complex<T> = { re: T; im: T; }
export const Complex_type = {
test: <T>(dep: { testT: (z: unknown) => z is T }) =>
(z: unknown): z is Complex<T> =>
typeof z === 'object' && z != null && 're' in z && 'im' in z
&& dep.testT(z.re) && dep.testT(z.im),
infer: (dep: typeOfDependency) =>
(z: Complex<unknown>) => joinTypes(dep.typeOf(z.re), dep.typeOf(z.im)),
from: {
T: <T>(dep: Dependency<'zero', [T]>) => (t: T) =>
({ re: t, im: dep.zero(t) }),
Complex: <U, T>(dep: { convert: (from: U) => T }) =>
(z: Complex<U>) => ({ re: dep.convert(z.re), im: dep.convert(z.im) })
}
}
export const complex_unary =
<T>(dep: {
zero: (z: T) => Complex<T>
}) =>
(t: T) => ({ re: t, im: dep.zero(t) })
export const complex_binary =
<T>(t: T, u: T): Complex<T> => ({ re: t, im: u })
export const zero =
<T>(dep: {
zero: (z: T) => T
}) =>
(z: Complex<T>): Complex<T> => complex_binary(dep.zero(z.re), dep.zero(z.im))
export const one =
<T>(dep: {
zero: (z: T) => T,
one: (z: T) => T
}) =>
(z: Complex<T>): Complex<T> => complex_binary(dep.one(z.re), dep.zero(z.im))
export const nan =
<T>(dep: {
nan: (z: T) => T
}) =>
(z: Complex<T>): Complex<T> => complex_binary(dep.nan(z.re), dep.nan(z.im))
export const re =
<T>(dep: {
re: (z: T) => T
}) =>
(z: Complex<T>): T => dep.re(z.re)