Skip to content

Instantly share code, notes, and snippets.

@eholk
Created November 22, 2012 01:40
Show Gist options
  • Select an option

  • Save eholk/4128950 to your computer and use it in GitHub Desktop.

Select an option

Save eholk/4128950 to your computer and use it in GitHub Desktop.
The Beginnings of a Matrix Library
use num::Num;
fn identity<T: Copy Num, M: matrix::BasicMatrix<T>>(N: uint) -> M {
matrix::create(N, N, |i, j| {
if i == j {
num::from_int::<T>(1)
}
else {
num::from_int(0)
}
})
}
mod matrix;
use matrix::Matrix;
use matrix::generate::identity;
fn main() {
let M : Matrix<float> = identity::<float, Matrix<float>>(2);
#error("%?", M);
}
mod generate;
pub trait BasicMatrix<T: Copy> {
static fn create(uint, uint, fn(uint, uint) -> T) -> self;
pure fn get(uint, uint) -> T;
fn set(uint, uint, T);
pure fn num_rows() -> uint;
pure fn num_cols() -> uint;
}
trait Vector<T: Copy> {
pure fn len() -> uint;
pure fn get(uint) -> T;
fn set(uint, T);
}
impl<T: Copy> Vector<T> : ops::Index<uint, T> {
pure fn index(i: uint) -> T {
self.get(i)
}
}
// It's nice to be able to use arbitrary vector slices as Vectors.
impl<T: Copy> &[mut T] : Vector<T> {
pure fn len() -> uint { vec::len(self) }
pure fn get(i: uint) -> T { self[i] }
fn set(i: uint, x: T) { self[i] = x }
}
// A matrix in Row-Major Order
pub struct Matrix<T: Copy> {
rows: uint,
cols: uint,
data: ~[mut T]
}
impl<T: Copy> Matrix<T> : BasicMatrix<T> {
static fn create(i: uint, j: uint, init: fn(uint, uint) -> T)
-> Matrix<T>
{
Matrix {
rows: i,
cols: j,
data: vec::to_mut(do vec::from_fn(i * j) |k| {
let i = k / j;
let j = k % j;
init(i, j)
})
}
}
pure fn get(i: uint, j: uint) -> T {
if i < self.num_rows() && j < self.num_cols() {
self.data[i * self.num_cols() + j]
}
else {
fail ~"Index out of bounds"
}
}
fn set(i: uint, j: uint, x: T) {
if i < self.num_rows() && j < self.num_cols() {
self.data[i * self.num_cols() + j] = x
}
else {
fail ~"Index out of bounds"
}
}
pure fn num_rows() -> uint { self.rows }
pure fn num_cols() -> uint { self.cols }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment