docs

您正在閱讀 v0.1.2 的文件。Nabi 0.1.2 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#Matrix operations

本頁內容

A small matrix type that implements the operator and index traits, so you can write a * b, a .* b and m[i, j].

#Code

#Walkthrough

  • Every operator in Nabi is a trait method call. With impl ops::Add for Matrix, a + a desugars to ops::Add::add(a, a) (3.1 Operator dispatch, Add, Mul).
  • The same operator can be implemented several times with different right-hand types. impl ops::Mul for Matrix is the matrix product and impl ops::Mul<f64> for Matrix is scalar multiplication; the compiler picks the impl from the operand types.
  • Dot-prefixed operators such as .* desugar to a separate trait family for element-wise operations (DotMul), so the matrix product * and the Hadamard product .* can live side by side. Inside, self.data .+ rhs.data and self.data .* k are the same operators on the List<f64> itself, one loop each with no intermediate list (3.3 Broadcast operators).
  • Comma indices are grouped into a tuple, so reading m[i, j] goes through Index<(usize, usize)> and writing m[i, j] = v through IndexSet<(usize, usize), f64>, whose second argument is the type of the value written. The write method takes ref self to modify the matrix in place (3.6 Indexing and slicing).
  • Thanks to impl Display for Matrix, {a} in an f-string prints the whole matrix. Each element uses {x:6.1} for width and precision (Structs, enums and traits).
  • This example shows how your own type joins the operators. For numeric work the core library already has Array<T, N>, an n-dimensional array with slicing, broadcasting and fused dot expressions (Arrays and numerics).

Found a mistake? Edit this page on GitHub. Last updated