core 接口
作用
luna-generic 是 LunaFlow 的代数 trait 基础层。它本身不提供数值算法或容器,而是给上层包提供共享的能力边界。
本页列出 trait、转换函数和随包提供的实例。证书 Hom 与 Section 见 hom API 页面。这些形态背后的理由见 core 设计。
导入
把本包加入你的 moon.pkg:
import {
"Luna-Flow/luna-generic",
}
本页示例用一条 using 声明把名字引入作用域,因此可以省略 @lf_alg. 前缀:
using @lf_alg {
trait AddMonoid,
trait MulMonoid,
trait AddGroup,
trait MulGroup,
trait Semiring,
trait Ring,
trait Field,
trait AddMonoidOps,
trait MulMonoidOps,
trait AddGroupOps,
trait MulGroupOps,
trait SemiringOps,
trait RingOps,
trait FieldOps,
trait NumOps,
trait RoundedArithmetic,
trait Zero,
trait One,
trait Inverse,
trait Conjugate,
trait FromNat,
trait FromInteger,
trait Integral,
trait Nat,
lift_to,
}
定律即契约
操作 bundle(AddMonoidOps、SemiringOps、RingOps、FieldOps 和 NumOps)描述可用的运算,但不声明等式。精确结构 trait(AddMonoid、Semiring、Ring、Field 等)要求返回不透明 Law[Theory, Self] 的方法。实现可以显式选择 Law::postulate() 假设,或通过内核拥有的蕴含关系推导较弱定律。编译器检查是否返回证书,不检查等式是否为真。
Float 与 Double 实现操作 bundle 和 RoundedArithmetic;它们不会获得精确的结构定律实例。
操作 trait
这些 trait 位于 src/operation.mbt。它们各自命名一个运算,本身不规定定律;结构 trait 赋予它们意义。
Zero
Zero::zero() 返回 Self 的加法单位元。
pub(open) trait Zero {
fn zero() -> Self
}
在 AddMonoid 中它必须满足 。所有默认数值类型都提供。
One
One::one() 返回 Self 的乘法单位元。
pub(open) trait One {
fn one() -> Self
}
在 MulMonoid 中它必须满足 。所有默认数值类型都提供。
test "zero and one" {
let z : Int = Zero::zero()
let o : Double = One::one()
inspect(z, content="0")
inspect(o, content="1")
}
Inverse
Inverse::inv(x) 返回乘法逆元 。
pub(open) trait Inverse {
fn inv(Self) -> Self
}
在 MulGroup 或 Field 中,对每个有逆元的 它必须满足 。随包提供的 Float 和 Double 实例在 0 上带消息中止,而不是像 1.0 / 0.0 那样返回无穷大。
test "inv" {
inspect(Inverse::inv(4.0), content="0.25")
}
Conjugate
Conjugate::conjugate(x) 返回共轭 。
pub(open) trait Conjugate {
fn conjugate(Self) -> Self
}
本包不提供任何实例。实现者通常让它成为与运算相容的对合:、 以及 ;当乘法可交换时后者即 。该 trait 并不强制这些定律。
priv struct Pair {
re : Double
im : Double
} derive(Eq, Debug)
impl Conjugate for Pair with fn conjugate(z) {
{ re: z.re, im: -z.im }
}
test "conjugate" {
let z = Pair::{ re: 1.0, im: 2.0 }
assert_eq(Conjugate::conjugate(Conjugate::conjugate(z)), z)
}
结构 traits
这些 trait 位于 src/structure.mbt。每个 trait 都返回不透明的定律证书。等式是由证书表示的契约;编译器不证明它们。
AddMonoid
AddMonoid 是带有可结合的 + 与单位元 0 的类型。
pub(open) trait AddMonoid : AddMonoidOps {
add_monoid_law() -> Law[AddMonoidTh, Self]
}
这里不要求 + 可交换;本包中所有建立在 AddMonoid 之上的结构(Semiring、Ring)都要求它可交换。
fn[T : AddMonoidOps] sum(xs : Array[T]) -> T {
xs.fold(init=Zero::zero(), (acc, x) => acc + x)
}
test "sum" {
inspect(sum([1, 2, 3]), content="6")
inspect(sum(([] : Array[UInt])), content="0")
}
MulMonoid
MulMonoid 是带有可结合的 * 与单位元 1 的类型。
pub(open) trait MulMonoid : MulMonoidOps {
mul_monoid_law() -> Law[MulMonoidTh, Self]
}
fn[T : MulMonoidOps] power(x : T, n : Int) -> T {
let mut acc : T = One::one()
for _ in 0..<n {
acc = acc * x
}
acc
}
test "power" {
inspect(power(3, 4), content="81")
inspect(power(2UL, 0), content="1")
}
AddGroup
AddGroup 是每个元素都有负元的 AddMonoid。
pub(open) trait AddGroup : AddGroupOps {
add_group_law() -> Law[AddGroupTh, Self]
}
无符号类型不实现它;见下文的语义说明。
fn[T : AddGroupOps] difference(x : T, y : T) -> T {
x + -y
}
test "difference" {
inspect(difference(3, 5), content="-2")
}
MulGroup
MulGroup 是带有逆元与除法的 MulMonoid。
pub(open) trait MulGroup : MulGroupOps {
mul_group_law() -> Law[MulGroupTh, Self]
}
Float 和 Double 为可执行运算实现 MulGroupOps,但不提供精确的 MulGroup 定律证书:0 没有逆元,浮点恒等式会发生舍入。
Semiring
Semiring 是关于半环运算的精确定律契约。
pub(open) trait Semiring : SemiringOps {
semiring_law() -> Law[SemiringTh, Self]
}
有符号和无符号整数类型以及 BigInt 提供显式的 SemiringTh 假设。Float 和 Double 提供 SemiringOps,但没有 Semiring 定律实例。
fn[T : SemiringOps] dot(xs : Array[T], ys : Array[T]) -> T {
let mut acc : T = Zero::zero()
for i, x in xs {
acc = acc + x * ys[i]
}
acc
}
test "dot" {
inspect(dot([1U, 2U, 3U], [4U, 5U, 6U]), content="32")
}
Ring
Ring 是关于环运算的精确定律契约。它的运算要求独立于证书。
pub(open) trait Ring : RingOps {
ring_law() -> Law[RingTh, Self]
}
RingTh 证书包含环公理;乘法不必可交换。编译器不证明返回证书所表示的等式。
fn[T : RingOps] square_of_difference(x : T, y : T) -> T {
(x - y) * (x - y)
}
test "ring" {
inspect(square_of_difference(2, 7), content="25")
}
Field
Field 是关于域运算的精确、非平凡交换域定律契约:,且每个非零元素都有逆元。
pub(open) trait Field : FieldOps {
field_law() -> Law[FieldTh, Self]
}
实现者必须满足 Ring 定律,并且对所有 :
非平凡性和交换性都是域的数学定义所要求的契约,但编译器都不会检查:只有一个元素的零环会空泛地满足逆元定律,乘法不可交换但有逆元的类型(除环)也能作为 Field 编译通过。依赖这些性质的泛型代码可能因此给出错误结果,例如把 改写为 。不要为这两类类型实现 Field。区别见 core 设计。
Float 和 Double 提供域运算,但没有 FieldTh 证书。它们的 inv 在 0 上中止,而 / 遵循 IEEE 754 并返回无穷大或 NaN。
fn[F : FieldOps] mean(xs : Array[F]) -> F {
let mut total : F = Zero::zero()
let mut count : F = Zero::zero()
for x in xs {
total = total + x
count = count + One::one()
}
total / count
}
test "field" {
inspect(mean([1.0, 2.0, 4.5]), content="2.5")
}
NumOps
NumOps 提供绝对值和符号运算,但不声明精确的环定律。旧的 Num trait 已移除。
pub(open) trait NumOps : RingOps {
fn abs(Self) -> Self
fn signum(Self) -> Self
}
signum(x) 按 的符号取 、 或 ,并且
由有符号整数、BigInt、Float 和 Double 实现。在定宽类型上,该恒等式在最小负值处失效,因为其绝对值会回绕为自身。在 Float 和 Double 上,signum 对 0.0、-0.0 和 NaN 返回参数本身。此操作 bundle 不蕴含 RingTh 定律。
test "num operations" {
inspect(NumOps::signum(-7), content="-1")
inspect(NumOps::abs(-7) * NumOps::signum(-7), content="-7")
}
整数转换
FromNat
FromNat::from_natural(n) 将非负的 BigInt 值转换为 Self。这个操作本身不证明转换保持半环运算。
pub(open) trait FromNat {
fn from_natural(@bigint.BigInt) -> Self
}
前置条件:。精确保持是独立的定律声明;舍入转换只是普通操作。
定宽整数按模 约化;Float 与 Double 舍入到最近的值,平局取偶,详见下文 FromInteger。
FromInteger
FromInteger::from_integer(n) 将 BigInt 值转换为 Self。它不会构造严格的 Hom 证书。
pub(open) trait FromInteger : FromNat {
fn from_integer(@bigint.BigInt) -> Self
}
它对每个整数都有定义,包括没有取负运算的类型:对无符号类型,from_integer(-1) 是 。对 BigInt 精确,对定宽整数按 取模,对 Float 和 Double 舍入。
对 Float 与 Double,from_integer(n) 是 IEEE 754 的 convertFromInt 转换:把 舍入到最近的、具有 位有效数字的值,Float 的 ,Double 的 ,平局时取有效数为偶数的那个。 的整数精确转换。舍入后的值超过最大有限数时,结果为 ;转换从不 abort:
| 目标类型 | 精确范围 | 结果为 的条件 |
|---|---|---|
Float | ||
Double |
零转换为 。core 设计推导了舍入规则和这些阈值。
test "from_integer" {
let big = BigInt::from_string("4294967301") // 2^32 + 5
let i : Int = FromInteger::from_integer(big)
let u : UInt = FromInteger::from_integer(BigInt::from_int(-1))
let d : Double = FromInteger::from_integer(big)
inspect(i, content="5")
inspect(u, content="4294967295")
inspect(d, content="4294967301")
}
test "from_integer into Double rounds and overflows" {
let two53 = BigInt::from_int(1) << 53
// 2^53 + 1 lies halfway between 2^53 and 2^53 + 2; the tie goes to 2^53.
let tie : Double = FromInteger::from_integer(two53 + BigInt::from_int(1))
let huge : Double = FromInteger::from_integer(BigInt::from_int(1) << 1024)
let tiny : Double = FromInteger::from_integer(-(BigInt::from_int(1) << 1024))
inspect(tie == 9007199254740992.0, content="true")
inspect(huge, content="Infinity")
inspect(tiny, content="-Infinity")
}
要让你自己的数值类型具备这些转换,请实现这两个 trait;core 教程 演示了做法。
整数类型
Integral
Integral 是整数类型:ℤ 本身,或者商 ℤ/2^k,例如定宽整数。
pub(open) trait Integral : Semiring + FromInteger {
fn normalize(Self) -> @bigint.BigInt
}
normalize(x) 以 BigInt 返回 x 的代表元。其定律是 normalize 为典范映射的截面:
随包实例的选择为:有符号类型取 ,无符号类型取 ,BigInt 取恒等映射。normalize 只对 BigInt 是同态;在定宽类型上不是,因为它们的运算会回绕。Section::of_integral 把这一对映射打包成可检查的证书。
test "normalize" {
inspect(Integral::normalize(-1), content="-1")
inspect(Integral::normalize(4294967295U), content="4294967295")
inspect(Integral::normalize(2147483647 + 1), content="-2147483648")
}
Nat
Nat 是代表元非负的 Integral 类型:对每个 x 有 。
pub(open) trait Nat : Integral {
}
由 UInt、UInt16 和 UInt64 实现。任意精度的 ℕ 不是 ℤ 的商,因此不能是 Integral;见 core 设计。
fn[N : Nat] digits(x : N) -> Int {
Integral::normalize(x).to_string().length()
}
test "nat" {
inspect(digits((65535 : UInt16)), content="5")
}
lift_to
lift_to(x) 把整数值提升为其代表元,再映入任意 FromInteger 目标。
pub fn[S : Integral, R : FromInteger] lift_to(S) -> R
它就是 R::from_integer(x.normalize())。它是函数而非同态:它转换的是 x 当前持有的值,所以已在 S 中回绕的和依旧是回绕后的值。当且仅当 R 的模数整除 S 的模数时它保持运算,例如 Int64 -> Int;core 设计 推导了这一条件。
test "lift_to" {
let a : Double = lift_to(-7)
let b : BigInt = lift_to(4294967295U)
let c : Int = lift_to(4294967301L) // truncation, a homomorphism
inspect(a, content="-7")
inspect(b, content="4294967295")
inspect(c, content="5")
}
随包提供的能力和定律
| 类型 | 操作能力 | 精确定律实例 |
|---|---|---|
Int, Int16, Int64 | AddMonoidOps, MulMonoidOps, AddGroupOps, SemiringOps, RingOps, NumOps | AddMonoid, MulMonoid, AddGroup, Semiring, Ring, CommRing |
UInt, UInt16, UInt64 | AddMonoidOps, MulMonoidOps, SemiringOps | AddMonoid, MulMonoid, Semiring, Nat |
BigInt | 有符号整数的操作能力和 NumOps | AddMonoid, MulMonoid, AddGroup, Semiring, Ring, CommRing, IntegralDomain |
Float, Double | AddMonoidOps, MulMonoidOps, AddGroupOps, MulGroupOps, SemiringOps, RingOps, FieldOps, NumOps, RoundedArithmetic | 无 |
Byte 不实现其中任何一个。
语义说明
- 定宽整数是 ℤ/2^k。它们的
from_integer按模 2^k 约化,normalize选取类型范围内的代表元:有符号类型为[-2^(k-1), 2^(k-1)),无符号类型为[0, 2^k)。 BigInt就是 ℤ 本身:from_integer与normalize都是恒等映射。lift_to当且仅当目标模数整除源模数时是同态,例如Int64 -> Int。对定宽源而言,映到BigInt、Float或Double都不是同态,因为源侧运算会回绕。Nat涵盖代表元非负的整数类型。真正的任意精度 ℕ 不是 ℤ 的商,不在本包范围内。- 无符号整数实例止步于
Semiring,不会伪装成带加法逆元的结构。 Float与Double在from_natural和from_integer中舍入到最近值、平局取偶,因此非常大的值是近似的,超出最大有限数的值变为 ,而不会 abort。- 返回的
Law[Th, Self]是显式假设;编译器不证明它的等式。Float和Double不会获得精确的域定律。
已弃用
NatHomomorphism
NatHomomorphism::from_nat(x) 把 Nat 值提升为其代表元,再映入 Self。
pub(open) trait NatHomomorphism {
fn[S : Nat] from_nat(S) -> Self
}
已弃用,因为对定宽源而言这一复合不是同态。替代方案:实现 FromNat 与 FromInteger,并调用 lift_to(x)。BigInt、Float 和 Double 仍实现它。
IntegralHomomorphism
IntegralHomomorphism::from_integral(x) 把 Integral 值提升为其代表元,再映入 Self。
pub(open) trait IntegralHomomorphism : NatHomomorphism {
fn[S : Integral] from_integral(S) -> Self
}
因同样的理由弃用。替代方案:实现 FromInteger 并调用 lift_to(x)。BigInt、Float 和 Double 仍实现它。
其他精确结构与理论标签
CommRing 要求在 RingOps 上提供 comm_ring_law() -> Law[CommRingTh, Self]:乘法可交换。IntegralDomain 要求在 RingOps 上提供 integral_domain_law() -> Law[IntegralDomainTh, Self]:它是无零因子的交换环。这两个 trait 都不提供 FieldTh 定律。
OrderedField 要求在 FieldOps + Compare 上提供 ordered_field_law() -> Law[OrderedFieldTh, Self]。其序是全序,与加法和非负值的乘法兼容。它为 G3 中精确的 Complex 体实例提供所需的确切前提;仅有 FieldTh 不够。
公开的空理论标签为 AddMonoidTh、MulMonoidTh、AddGroupTh、MulGroupTh、SemiringTh、RingTh、CommRingTh、IntegralDomainTh、FieldTh、OrderedFieldTh、IntegralTh、NatTh 和 IntegerHomomorphismTh。IntegralTh 记录代表元往返定律;NatTh 还记录代表元非负。IntegerHomomorphismTh 记录 BigInt 转换的精确保持性,不要求单射。
定律构造与内核规则
Law::postulate() 是任意理论与载体的显式信任入口,不证明方程。弱化方法接收较强定律,只返回所指的较弱定律。积方法接收两个分量的定律,返回 Prod[A, B] 上同一理论的定律。
pub fn[Th, A] Law::postulate() -> Law[Th, A]
pub fn[A] Law::semiring_to_add_monoid( _law : Law[SemiringTh, A], ) -> Law[AddMonoidTh, A]
pub fn[A] Law::semiring_to_mul_monoid( _law : Law[SemiringTh, A], ) -> Law[MulMonoidTh, A]
pub fn[A] Law::ring_to_semiring(_law : Law[RingTh, A]) -> Law[SemiringTh, A]
pub fn[A] Law::ring_to_add_group(_law : Law[RingTh, A]) -> Law[AddGroupTh, A]
pub fn[A] Law::add_group_to_add_monoid( _law : Law[AddGroupTh, A], ) -> Law[AddMonoidTh, A]
pub fn[A] Law::comm_ring_to_ring(_law : Law[CommRingTh, A]) -> Law[RingTh, A]
pub fn[A] Law::integral_domain_to_ring(_law : Law[IntegralDomainTh, A]) -> Law[RingTh, A]
pub fn[A] Law::field_to_ring(_law : Law[FieldTh, A]) -> Law[RingTh, A]
pub fn[A] Law::field_to_comm_ring(_law : Law[FieldTh, A]) -> Law[CommRingTh, A]
pub fn[A] Law::field_to_integral_domain( _law : Law[FieldTh, A], ) -> Law[IntegralDomainTh, A]
pub fn[A] Law::field_to_semiring(_law : Law[FieldTh, A]) -> Law[SemiringTh, A]
pub fn[A] Law::ordered_field_to_field( _law : Law[OrderedFieldTh, A], ) -> Law[FieldTh, A]
pub fn[A, B] Law::product_add_monoid( _left : Law[AddMonoidTh, A], _right : Law[AddMonoidTh, B], ) -> Law[AddMonoidTh, Prod[A, B]]
pub fn[A, B] Law::product_mul_monoid( _left : Law[MulMonoidTh, A], _right : Law[MulMonoidTh, B], ) -> Law[MulMonoidTh, Prod[A, B]]
pub fn[A, B] Law::product_add_group( _left : Law[AddGroupTh, A], _right : Law[AddGroupTh, B], ) -> Law[AddGroupTh, Prod[A, B]]
pub fn[A, B] Law::product_semiring( _left : Law[SemiringTh, A], _right : Law[SemiringTh, B], ) -> Law[SemiringTh, Prod[A, B]]
pub fn[A, B] Law::product_ring( _left : Law[RingTh, A], _right : Law[RingTh, B], ) -> Law[RingTh, Prod[A, B]]
源码入口
src/structure.mbt:trait 定义src/operation.mbt:基础操作 traitssrc/section.mbt:lift_tosrc/impl_signed.mbt、src/impl_unsigned.mbt、src/impl_bigint.mbt、src/impl_float.mbt、src/impl_dbl.mbt:默认实例