Christopher Smith wrote:
> Tracy R Reed wrote:
>   
>> Gabriel Sechan wrote:
>>     
>>> Seriously, though.  A variable *always* has a type, wether the
>>> language does or not.  The type of a variable is the kind of data it
>>> holds.  This is separate from its languae type.  For example, lets
>>> say we have to store today's temperature.  Its type is temperature in
>>> degree's celsius.  Its language type may be scalar in perl, int in
>>> C++, etc.  But its true type is still temperature in degrees
>>> celsius.  Having a language that supports typedefs and declarations
>>> merely documents that for you, rather than forcing you to read the
>>> code to figure it out.
>>>       
>> Can you somehow encapsulate units in a type so that when we program a
>> completely hypothetical Mars lander it doesn't allow us to
>> accidentally mix meters and feet without doing a type conversion?
>>     
> Yes, actually you can. Sadly Martin Fowler wrote up exactly how to do
> this in Analysis Patterns long before the mission, haskell folks do this
> kind of stuff in their sleep, and the boost folks have encoded it in
> their "units" library. With a statically typed language you can even get
> it to produce compile time errors for this kind of fuck up.
>   
I should have provided a link to the units library:

http://svn.boost.org/svn/boost/sandbox/units/

--Chris

P.S.: The basic design pattern is that you have "measurements"
(sometimes people call them quantities), which are made up of two parts:
a "magnitude" and a "unit of measurement" (usually just called a
"unit"). You then define mathematical operations for measurements as
operations that transform both the magnitude and the unit. Sometimes the
magnitude is represented as a rational number (often it is more like a
decimal number with a specified precision), but the unit is effectively
always represented that way. You need to build a heuristics for
reducing, converting and testing equivalence of units, and often
magnitudes as well. It all works wonderfully if you can make the library
rich enough (C++ templates, for all their syntactical baroqueness, are
extremely powerful for cases like this), you'll find it impossible to
compile code that steps outside the bounds of what you have defined as
possible/correct.

If something like this had been done for the Mars lander mission, one of
two things would have happened: either the library would have failed
because it had no heuristics for transforming from one meters to feet,
or it would have automagically done the conversion and nobody would have
even realized that different teams were using different units, because
utlimately it wouldn't have mattered, so long as their measurements were
accurately represented.

-- 
[email protected]
http://www.kernel-panic.org/cgi-bin/mailman/listinfo/kplug-lpsg

Reply via email to