Neat: UFCS for integer dot operator suffix
David Piepgrass
qwertie256 at gmail.com
Mon Sep 24 10:48:24 PDT 2012
>> I used this in a small unit library (partially accessible on
>> github),
>> to obtain code like:
>>
>> auto distance = 100.km;
>> auto speed = 130.km/h; // division works, too.
>>
>> auto timeToDestination = (distance/speed).hour; //
>> distance/speed
>> gives seconds => transformed in hours.
>>
>> It was a nice exercise in using UFCS and mixins to create your
>> own
>> unit library (not only IS, but ay kind of unit library).
>>
>> And, you know what? I *never* used it after coding it. These
>> examples
>> are cute, they make for nice blog posts for F#, but the
>> real-world
>> usage is dubious to me (I know they were space-programs
>> crashes)
>>
>> I quite like the implicit message in units: use the type
>> system to
>> help you catch errors are compile-time. Add to that a nice
>> syntax and
>> a showcase for D's generational capabilities and it's quite
>> nice.
>>
>> But, to my eyes, it's but a toy.
>
> I wouldn't read too much into it. You're a library author, not
> (I assume) a scientific computing guy. So beyond playing with a
> few examples, your work on this library is done - you wouldn't
> be a client of it for the simple reason you don't intensively
> work with kilometers, speeds, dollars, and such. It's possible
> that a good and usable library of units could add value to a
> category of users.
IMO, you don't need to be a scientific computing guy to find unit
checking useful, since almost any number conceptually has a unit
on it. I would ask any programmer, how often do you accidentally
use a measurement of 'bytes' where 'dwords' were expected, or use
a variable as an array index when it was actually something
totally different?
However, unit checking cannot be done satisfactorially in a
library; it has two main problems when provided that way:
1. It's too bulky (too much syntax required, as units have to be
spelled out constantly)
2. Values with traditionally-typed units don't interoperate with
existing libraries, including very simple functions such as
int abs(int x) { return x > 0 ? x : -x; }
int square(int x) { return x*x; }
You can define an inplicit conversion from e.g. 'Unit!"pixels"'
to 'int' but then you'll need to manually cast it back, and the
compiler can't check your cast to make sure it's correct.
IMO, solving these two problems requires a parallel type system
to infer unit relationships automatically, either with direct
language support, or a separate analysis tool that uses the
compiler as a service (currently not possible with D).
More information about the Digitalmars-d
mailing list