Better number literals


#41

Just to note I find current syntax fine for Latitude and Longitude:

val penzance = 50.06 ll -5.68
val trevoseHead = 50.55 ll -5.03
val nwDevon = 51.18 ll -4.19
val parrettMouth = 51.21 ll -3.01
val chepstow = 51.61 ll -2.68
val stDavids = 51.88 ll -5.31   

#42

All of these suggestions are nice, but at the end of the day, they’re asking a lot from what the language accepts as a literal. My proposal is just to allow _ within literals, with no extra syntactic or semantic meaning. This is not meant to make it possible to write BigDecimal or IP literals; just to make it easier to read existing number literals.

If you’re writing a library that uses a lot of binary or hex constants for fancy bitwise magic, or numeric constants for mathematical witchcraft, adding an _ periodically in the literal can drastically improve readability.

val magicNumber = 0b10000001010001100000000000100001
// vs
val magicNumber = 0b_1000_0001_0100_0110_0000_0000_0010_0001

The latter separates the 32bit number into 4bit chunks, making it easier to process the number mentally without accidentally skipping a bit or losing track of whether you’re at the 17th or 18th bit.

You might even add extra _s in the middle to break up the sections even more visibly (since there are 8 of them, which is a decent number)

val magicNumber = 0b_1000_0001_0100_0110__0000_0000_0010_0001

I would like to keep this proposal to the bare minimum of improving readability of literals, without attempting to allow defining new literals for arbitrary types. I think it could be valuable to allow the definition of arbitrary literals as well, but that requires significantly more work and is a major language change, while being slightly more flexible with existing literals requires less design discussion and bikeshedding.


#43

That sounds fine, so long as 0x_ desugars to Integer.parseInt(_, 16).


#44

That sounds right to me (at compile time, I assume)


#45

I agree. We still can use string interpolation for the other stuff, which is good enough I think.


#46

I disagree :))
We often write something like:

val a = 10.nn  /* return BigDecimal  with null support*/

If we need a real number we must write:

val a = "10.1".nn 
or 
val a = nn"10.1"

But in pattern matching we always must use string interpolation.

We have a lot of dibate on it, like:

I think it is great when the language can make such debate redundant.

When 80% of numeric constants is Bigdecimal in your business logic, such debate really annoy