rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
731 stars 135 forks source link

feat: implement first naive version of induction #297

Closed RobWalt closed 1 year ago

RobWalt commented 1 year ago

I see a lot of crates using things like

let two = T::one() + T::one();

I've seen this multiple times in geo while working on different areas there. This PR implements a trait Induction which has a method nth which can be used as follows

let two = T::nth<2>();
let five = T::nth<5>();

I'm not sure if you think that this abstraction is worth it. I personally feel this removes a bit of boilerplate code and also reads nicer.

This PR is open for review, but please don't merge it yet as I'll add some more docs + tests at some point in the near future.

cuviper commented 1 year ago

Couldn't you use the cast traits for this? e.g. where T: FromPrimitive => let five = T::from_u8(5).unwrap();

To avoid the unwrap, plain From can be used for infallible conversions in many cases: From<i8> works for all floats and signed integer types, or From<u8> works for all floats and integers except i8.

RobWalt commented 1 year ago

Yeah you're right. This approach also doesn't produce as much overhead as repeatingly calling T::one. Although I somehow dislike the fact that we need to unwrap, I also see that it's needed and that I didn't treat that case at all yet. Closing this here then.