Crystal: Implement a rational data type

Created on 18 Jan 2018  ·  7Comments  ·  Source: crystal-lang/crystal

Built-in rational data type will give the ability to represent numbers like 1/3 and -11/17 without rounding.

There are different options: defaulting to the rational type when using 1/10 or using ruby inspired syntax with 1/10r

Most helpful comment

We have BigRational... It's not in the corelib so there won't be literals for it.

All 7 comments

We have BigRational... It's not in the corelib so there won't be literals for it.

My opinion, some will disagree, is to defaulting to Rational number when 1/2 is used, and to Float when 0.5 used. Discussion is open.

@j8r 1/2 is parsed as 1 / 2 i.e. 1./(2) (a method call). This isn't possible. I wouldn't want it even if it was possible. Floats and Ints are the standard numeric types in software today. If you want other types, you need libraries for it, like Big*

@RX14 Ok, I see. So a ruby like literal like 1/10r is more conceivable.

@j8r no. There will never be a literal for rationals. Use the BigRational constructor.

@RX14 BigRational is not the same as Rational ─ which would be a smaller and more primitive type (and maybe generic? ─ I dunno how it'd be best to implement).

The issue "Implement a rational data type," does not necessarily prompt for a literal or operations on integers to return them. If there is no better way we can at least construct them manually Rational32.new 1, 3, or generic Rational(Int32), ─ hell, maybe even something à la IntX: Rat32.

I think this should be reopened, rationals are very nice to work with.

@Jens0512 For this to be reopened, there should be a reasonable cause why BigRational isn't enough. I don't think there is any.

Was this page helpful?
0 / 5 - 0 ratings