Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Const generics🧮 #79

Merged
merged 29 commits into from
Sep 8, 2024
Merged

Const generics🧮 #79

merged 29 commits into from
Sep 8, 2024

Conversation

adam-mcdaniel
Copy link
Owner

@adam-mcdaniel adam-mcdaniel commented Sep 6, 2024

With this PR, you can write code like:

struct Matrix<T, const Rows: Int, const Cols: Int> {
    arr: [[T * Cols] * Rows]
}

impl Matrix<T, Rows, Cols> {
    fun new(x: T): Matrix<T, Rows, Cols> {
        return {arr=[[x] * Cols] * Rows};
    }

    fun get(&self, row: Int, col: Int): &T {
        return &self.arr[row][col];
    }

    fun mul<const NewCols: Int>(
        &self,
        other: &Matrix<T, Cols, NewCols>,
        zero: T,
        add: fun(T, T) -> T,
        mul: fun(T, T) -> T
    ): Matrix<T, Rows, NewCols> {
        let mut result = Matrix.new<T, Rows, NewCols>(zero);
        for let mut j=0; j<NewCols; j+=1; {
            for let mut i=0; i<Rows; i+=1; {
                let mut sum = zero;
                for let mut k=0; k<Cols; k+=1; {
                    sum = add(sum, mul(self.arr[i][k], other.arr[k][j]));
                }
                result.arr[i][j] = sum;
            }
        }
        result
    }
}

let mut x = Matrix.new<Int, 4, 4>(10);
let mut y = Matrix.new<Int, 4, 4>(5);

println(x);
println(y);

fun add_ints(a: Int, b: Int): Int = a + b;
fun mul_ints(a: Int, b: Int): Int = a * b;

let z = y.mul<4>(&x, 0, add_ints, mul_ints);
println(z);

@adam-mcdaniel adam-mcdaniel added enhancement New feature or request Frontend📝 The frontend source code language Typechecking⚠️ Relating to the typechecker labels Sep 7, 2024
@adam-mcdaniel adam-mcdaniel merged commit a4a2e85 into main Sep 8, 2024
1 check passed
@adam-mcdaniel adam-mcdaniel deleted the const-generics branch September 8, 2024 10:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request Frontend📝 The frontend source code language Typechecking⚠️ Relating to the typechecker
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant