How can I write a Rust macro to convert row-major order to column-major order?

Viewed 219

The macro would allow you to write any M x N matrix in a natural way. For example:

matrix![
    1.0, 3.0, 5.0;
    2.0, 4.0, 6.0;
]

which corresponds to the following matrix.

┌                 ┐
│  1.0  3.0  5.0  │
│  2.0  4.0  6.0  │
└                 ┘

The macro would output an array of arrays like the following:

[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]

I know that I can parse row-major order quite simply using the following. But how can I can convert this to a column-major order. I can't figure out how to switch the order of the repeating groups.

macro_rules! matrix {
    ($($($e:expr),*);*) => {(
        [$([$($e),*]),*]
    }
}
1 Answers

Here you go:

macro_rules! matrix {
    ($($($v:expr),* );*) => {
        matrix!(@phase2 [] $($($v),* );*)
    };
    (@phase2 [$([$($col:expr),*])*] $($v:expr);* ) => {
        [$([$($col),*],)* [$($v),*]]
    };
    (@phase2 [$([$($col:expr),*])*] $($v0:expr, $($v:expr),* );* $(;)?) => {
        matrix!(@phase2 [$([$($col),*]),* [$($v0),*]] $($($v),* );*)
    };
}
Related