paholg / typenum

Compile time numbers in Rust.
https://crates.io/crates/typenum
Other
508 stars 45 forks source link

Provide macros for convenience. #62

Closed ticki closed 7 years ago

ticki commented 7 years ago

Things like allowing to use familiar syntax to do arithmetics and the alike.

num!(A+B)
cond!(A < B)
paholg commented 7 years ago

Type-level macros are still experimental, so if implemented, this would have to be behind a feature flag for now.

A macro that can do a single operation would be easy to implement, but it would be nice to have one that can handle full expressions. I think it will be quite difficult to get order of operations correct.

E.g. I'm not sure how to make it parse both A + B * C and A * B + C correctly.

One solution would be to use reverse polish notation.

paholg commented 7 years ago

As of rust 1.13.0 (the current beta) type macros are stable, so we should be able to put this in soon.

paholg commented 7 years ago

I would like to implement this in a complete way, allowing arbitrary arithmetic in the macro call.

This Stack Overflow answer does just that: http://stackoverflow.com/a/36800597/2977291

I was unsure about licenses, so I looked it up, and it seems it's covered under an MIT license, so we could just use that, with alterations to make it work for types.

It would be nice, though, to include more than just the four basic arithmetic operations; at least exponents would be good, and maybe even roots and the like. The algorithm in that macro grows (in number of lines) exponentially with number of operators, though. I wonder if we could do something cleverer to reduce that?

paholg commented 7 years ago

This algorithm looks promising: https://en.wikipedia.org/wiki/Shunting-yard_algorithm

paholg commented 7 years ago

@ticki Well, I finally got around to this. Give me a shout if you find it's missing anything.