RFC: Units of measurement for D (Phobos?)

David Nadlinger via Digitalmars-d digitalmars-d at puremagic.com
Fri Mar 18 20:27:33 PDT 2016


On Thursday, 17 March 2016 at 12:51:28 UTC, Nordlöw wrote:
> I believe `isConvertableTo` is a more Phobos-compliant naming, 
> right?

I went for canConvert since it is a bit shorter than 
isConvertible and there is precedent for it in Phobos as well 
(e.g. find/canFind). It's a matter of taste, though. If I were to 
work on the library again today, I might just as well go for 
isConvertible.

> Is there are reason why `convert` wasn't named the shorter and 
> Phobos-compliant `to` instead?

One thing to consider is that convert!U differs from to!T in that 
the latter returns something of type T, whereas the former 
returns a Quantity!(U, …). This seems enough of a difference that 
choosing the same name as the widely used std.conv.to might be 
somewhat misleading (even though I usually advocate for using the 
module system for disambiguating names).

>> function, you then simply use cos(angle.convert!radian / 
>> radian) or whatever.
>
> Why not simply add a Quantity member […] toValue()

This is again a design decision that can go either way. The 
choice I made was deliberate, although of course not above debate:

Since I chose to have dimensionless quantities implicitly convert 
to "plain" value types, it seemed superfluous to add another 
primitive (`a / a.unit` is simple enough to write). Furthermore, 
it underlines the point that `*` and `/` between quantities and 
units do not actually change the numeric value, but merely modify 
its units. Making use of that for the "core functionality" seemed 
like a cute way to drive the point home to users. Explicitly 
specifying the unit also helps avoiding mistakes in generic code.

If you want to go the other route, I would suggest carefully 
deliberating the naming scheme, since discarding unit information 
is a lossy and potentially "unsafe" (as in code correctness). In 
an attempt to make this obvious in the current implementation 
(where it is only enabled for dimensionless quantities), I named 
the function rawValue(). For example, renaming (fromValue, 
rawValue) to {from, to}Raw() might be clearer than {from, 
to}Value().

By the way, I highly doubt that "puts less stress on the 
compiler" is a valid argument for that decision. In that regard, 
the big elephant in the room is GetConversion, which you might 
want to re-do using a breadth-first search anyway (see TODO 
comments; I couldn't be bothered to implement it back then due to 
the numerous DMD bugs I had to fight).

  — David


More information about the Digitalmars-d mailing list