internal API

Luna-Flow/linear-algebra/internal 存放 immut 与 mutable 共用的形状检查辅助函数。它定义了 HasShape trait,并为每个前置条件提供一个返回 Result[Unit, LinearAlgebraError] 的受检守卫和一个会中止的守卫。

源码:src/internal/algebra.mbt。

HasShape

HasShape 报告类矩阵值的 (rows, cols)。

pub(open) trait HasShape {
  fn shape(Self) -> (Int, Int)
}

由 @immut.Matrix、@immut.MatrixFn 和 @mutable.Matrix 实现。它与 @algebra.MatrixShape 相对应,但位于 algebra 之下,因此具体包无需依赖实验性的 algebra 层。

HasShape::shape

HasShape::shape(m) 返回 (rows, cols)。

fn HasShape::shape(Self) -> (Int, Int)

守卫

每个前置条件都有两种形式。_checked 形式在前置条件成立时返回 Ok(()),否则返回所列类型的 Err。普通形式返回 (),或以该错误的消息中止。对任意输入,ensure_x(m) 中止当且仅当 ensure_x_checked(m) 为 Err。

守卫前置条件错误类型
ensure_square行数 = 列数NonSquareMatrix
ensure_row_in_bounds0≤r<0 \le r < 行数IndexOutOfBounds
ensure_col_in_bounds0≤c<0 \le c < 列数IndexOutOfBounds
ensure_index_in_bounds行与列均在范围内(先检查行)IndexOutOfBounds
ensure_same_shapeshape(a) == shape(b)DimensionMismatch
ensure_mul_compatiblecols(a) = rows(b)DimensionMismatch

ensure_square, ensure_square_checked

pub fn[M : HasShape] ensure_square(M) -> Unit
pub fn[M : HasShape] ensure_square_checked(M) -> Result[Unit, @error.LinearAlgebraError]

ensure_row_in_bounds, ensure_row_in_bounds_checked

pub fn[M : HasShape] ensure_row_in_bounds(M, Int) -> Unit
pub fn[M : HasShape] ensure_row_in_bounds_checked(M, Int) -> Result[Unit, @error.LinearAlgebraError]

ensure_col_in_bounds, ensure_col_in_bounds_checked

pub fn[M : HasShape] ensure_col_in_bounds(M, Int) -> Unit
pub fn[M : HasShape] ensure_col_in_bounds_checked(M, Int) -> Result[Unit, @error.LinearAlgebraError]

ensure_index_in_bounds, ensure_index_in_bounds_checked

pub fn[M : HasShape] ensure_index_in_bounds(M, Int, Int) -> Unit
pub fn[M : HasShape] ensure_index_in_bounds_checked(M, Int, Int) -> Result[Unit, @error.LinearAlgebraError]

ensure_same_shape, ensure_same_shape_checked

pub fn[A : HasShape, B : HasShape] ensure_same_shape(A, B) -> Unit
pub fn[A : HasShape, B : HasShape] ensure_same_shape_checked(A, B) -> Result[Unit, @error.LinearAlgebraError]

ensure_mul_compatible, ensure_mul_compatible_checked

pub fn[A : HasShape, B : HasShape] ensure_mul_compatible(A, B) -> Unit
pub fn[A : HasShape, B : HasShape] ensure_mul_compatible_checked(A, B) -> Result[Unit, @error.LinearAlgebraError]

两个操作数可以是不同类型,例如一个 Matrix 和一个 MatrixFn。

示例

这些守卫无法从仓库外部导入;它们的效果通过基于它们构建的公开方法体现:

///|
test "guards behind public methods" {
  let a = @immut.Matrix::from_2d_array([[1, 2, 3]])
  match a.matmul(a) {
    Err(e) =>
      inspect(
        e.message,
        content="Matrix dimensions are not compatible for multiplication",
      )
    Ok(_) => fail("1x3 times 1x3 is not defined")
  }
  match a.trace() {
    Err(e) => inspect(e.message, content="Matrix must be square")
    Ok(_) => fail("a 1x3 matrix has no trace")
  }
  debug_inspect(a.shape(), content="(1, 3)")
}