Skip to content

Commit e19d676

Browse files
committed
added matmul example
1 parent 99af77b commit e19d676

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,6 @@ in a controlled repository now.
2424
* `sum.rs`: generic iterator sum example
2525
* `addy.rs`: trait def/impl example
2626
* `bno-salad.rs`: trait salad example from Blandy and Orendorff
27+
* `matmul.rs`: example of overloading multiplication for matrices
2728
* `custom_sum.rs`: sum example with custom `Sum` type
2829
* `phantom.rs`: phantom type example

matmul.rs

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
use std::ops::*;
2+
3+
#[derive(Debug, Clone, Copy)]
4+
struct Matrix3([[u64;3];3]);
5+
6+
impl Mul for Matrix3 {
7+
type Output = Matrix3;
8+
9+
fn mul(self, Matrix3(rhs): Self) -> Self {
10+
let Matrix3(lhs) = self;
11+
let mut result = [[0;3];3];
12+
for i in 0..3 {
13+
for j in 0..3 {
14+
for k in 0..3 {
15+
result[i][k] += lhs[i][j] * rhs[j][k];
16+
}
17+
}
18+
}
19+
Matrix3(result)
20+
}
21+
}
22+
23+
impl PartialEq for Matrix3 {
24+
fn eq(&self, &Matrix3(ref rhs): &Matrix3) -> bool {
25+
self.0 == *rhs
26+
}
27+
}
28+
29+
const TTT: Matrix3 = Matrix3(
30+
[[1,2,3],
31+
[4,5,6],
32+
[7,8,9]]
33+
);
34+
35+
const ID: Matrix3 = Matrix3(
36+
[[1,0,0],
37+
[0,1,0],
38+
[0,0,1]]
39+
);
40+
41+
const MAGIC: Matrix3 = Matrix3(
42+
[[6,1,8],
43+
[7,5,3],
44+
[2,9,4]]
45+
);
46+
47+
fn main() {
48+
assert_eq!(TTT * ID, TTT);
49+
assert_eq!(ID * TTT, TTT);
50+
assert!(TTT * MAGIC != MAGIC * TTT);
51+
println!("{:?}", TTT * TTT);
52+
}

0 commit comments

Comments
 (0)