"Strong typing vs. strong testing"
Erik Max Francis
max at alcyone.com
Tue Sep 28 18:02:10 EDT 2010
Malcolm McLean wrote:
> On Sep 27, 9:29 pm, p... at informatimago.com (Pascal J. Bourguignon)
> wrote:
>> On the other hand, with the dynamic typing mindset, you might even wrap
>> your values (of whatever numerical type) in a symbolic expression
>> mentionning the unit and perhaps other meta data, so that when the other
>> module receives it, it may notice (dynamically) that two values are not
>> of the same unit, but if compatible, it could (dynamically) convert into
>> the expected unit. Mission saved!
>>
> I'd like to design a language like this. If you add a quantity in
> inches to a quantity in centimetres you get a quantity in (say)
> metres. If you multiply them together you get an area, if you divide
> them you get a dimeionless scalar. If you divide a quantity in metres
> by a quantity in seconds you get a velocity, if you try to subtract
> them you get an error.
There are already numerous libraries that help you with this kind of
things in various languages; Python (you're crossposting to
comp.lang.python), for instance, has several, such as Unum, and
including one I've written but not yet released. It's not clear why one
would need this built into the language:
>>> print si
kg m s A K cd mol
>>> length = 3*si.in_ # underscore is needed since `in` is a keyword
>>> print length
3.0 in_
>>> lengthInCentimeters = length.convert(si.cm)
>>> print lengthInCentimeters
7.62 cm
>>> area = lengthInCentimeters*lengthInCentimeters
>>> print area
58.0644 cm**2
>>> biggerArea = 10.0*area
>>> ratio = area/biggerArea
>>> print ratio
0.1
>>> speed = (3.0*si.m)/(1.5*si.s)
>>> print speed
2.0 m/s
>>> ratio - speed
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "unity.py", line 218, in __sub__
converted = other.convert(self.strip())
File "unity.py", line 151, in convert
raise IncompatibleUnitsError, "%r and %r do not have compatible
units" % (self, other)
__main__.IncompatibleUnitsError: <Quantity @ 0x-4814a834 (2.0 m/s)> and
<Quantity @ 0x-4814a7d4 (1.0)> do not have compatible units
And everybody's favorite:
>>> print ((epsilon_0*mu_0)**-0.5).simplify()
299792458.011 m/s
>>> print c # floating point accuracy aside
299792458.0 m/s
--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis
In Heaven all the interesting people are missing.
-- Friedrich Nietzsche
More information about the Python-list
mailing list