arithmetic

本手册描述 Luna-Flow/arithmetic 的 0.5.0 版本,以及 CHANGELOG.md 中列出的尚未发布的 MoonBit 0.10 迁移。

概览

Luna-Flow/arithmetic 定义 Luna Flow 数值类型的分析能力:初等函数;返回结构化错误的检查运算;在显式精度和舍入模式下报告结果如何被舍入的上下文运算;以及区间等包络之间的关系。它为 Float、Double 和整数类型提供默认实例,而把忠实遵循上下文的算术和经认证的算术留给实现同一组 trait 的后端。

luna-generic 说明一个类型是什么(Ring、Field 等)。arithmetic 说明它支持哪些分析运算以及这些运算如何失败。数值后端实现这些 trait,算法依赖这些 trait 而不是具体的数值类型。

层级示例返回适用场景
非检查Sqrt::sqrtSelf可以接受该类型自身的特殊值行为
检查SqrtChecked::sqrt_checkedResult[Self, ArithmeticError]无效输入必须变成可处理的错误
上下文SqrtContextual::sqrt_contextualResult[ArithmeticOutcome[Self], ArithmeticError]精度和舍入是显式的,且诊断很重要
包络关系DefinitelyLt::definitely_ltBool值是区间或球,而不是点

安装

moon add Luna-Flow/arithmetic@0.5.2

然后在你的 moon.pkg 中导入 "Luna-Flow/arithmetic"。Luna Flow 代码使用别名 @lf_arith:

import {
  "Luna-Flow/arithmetic" @lf_arith,
}

本包需要 MoonBit 工具链 0.10.20 或更高版本(moonc ≥ 0.10.20),使用 moon.mod 和 moon.pkg 清单,并在 wasm-gc、wasm、js 和 native 后端上进行检查。Float 和 Double 的初等函数依赖 Kaida-Amethyst/math;测试还用到 Luna-Flow/luna-generic。

页面

本模块只有一个包,位于源码根目录 src/,文档中称为 core。

部分教程API设计
core:能力 trait、上下文、诊断、错误、实例教程API设计

覆盖整个包的指南:

指南内容
入门安装、第一个泛型函数、第一次检查调用和上下文调用
架构源码布局、层级、错误与状态
验证本地检查关卡、CI 以及测试所确立的内容
仓库约定在 Luna Flow 标准之上适用于本手册的规则

黑盒测试(src/*_test.mbt)和白盒测试(src/certification_error_wbtest.mbt)属于同一个包;验证指南列出了它们所确立的内容。

导出的 trait

  • 非检查:Sqrt、Cbrt、Radical、Exponential、Logarithmic、Power、Trigonometric、InverseTrigonometric、Hyperbolic、InverseHyperbolic、Constants
  • 检查:SqrtChecked、DivChecked、CompareChecked、PowNatChecked、PowIntChecked、ParseChecked
  • 上下文:AddContextual、SubContextual、MulContextual、DivContextual、AbsContextual、SqrtContextual、ExpContextual、IntegralContextual、AdjacentContextual、ConstantsContextual、HyperbolicContextual、NumericFormatContextual
  • 包络关系:Contains、Overlaps、DefinitelyLt、DefinitelyLe、MaybeEq

导出的类型

  • 上下文:ArithmeticContext 及其预设 decimal32、decimal64 和 decimal128,以及 RoundingMode
  • 结果:ArithmeticOutcome[T] 和 ArithmeticDiagnostics
  • 错误:ArithmeticError、ArithmeticErrorKind,以及认证证据 CertificationFailureDetail、CertificationStage 和 CertificationFailureReason
  • 分类:FpClass

内置实例

  • Float 和 Double:所有非检查 trait,除 ParseChecked 外的所有检查 trait,以及上下文算术、绝对值、平方根、指数、整数嵌入、相邻值和格式查询
  • Int、Int16、Int64、UInt、UInt16、UInt64 和 BigInt:仅 Power
  • ParseChecked、ConstantsContextual、HyperbolicContextual 和包络关系没有随包实例,由后端提供

core 教程用每个层级完成实际任务。core API 列出每个公开项以及每个随包实例在边界情形下的行为,core 设计推导契约背后的舍入、包络和误差界数学。

  • 初次接触本包:先阅读入门,再阅读 core 教程。
  • 在库中使用它:随手备好 core API;其中的表格说明了每个随包实例在边界情形(NaN、零、无穷、上溢)下的实际行为。
  • 实现后端或参与贡献:阅读 core 设计了解契约及其数学,阅读架构了解代码布局,并在发起 pull request 之前阅读验证和约定。

验证

推荐的发布检查:

moon check --target all
moon test
moon test --target js
moon test --target native

验证指南给出完整的检查关卡,包括文档检查。