Automatic Type Conversions

Writing unit tests is a great thing. It makes you think even harder than usually about the semantics of your code.

In Babel-17 you have real interval arithmetic; for example, to describe the interval between 4 and 5, you could write [4.0; 5.0]. This notation, [a;b] assumes that a and b are reals, and forms the convex hull that contains both a and b.

Now. Should it be possible to also write [4; 5] for the above interval?

In my current preliminary spec for Babel-17 v0.3 the answer is NO. An integer is not a real; for example you cannot compare them, 2 == 2.0 evaluates to false. This point of view has a lot going for it; it seems pure.

(Un)fortunately, people don’t care so much about purity. I can already see the looks on faces when I try to explain that [4.0; 5.0] is a real interval, but [4; 5] is not even a legal expression.

There is an obvious solution to this dilemma: type conversions. These are already a part of Babel-17 v0.3: for example, 3 :> real converts the integer 3 to the real 3.0 .

Type conversions could be used such that whenever I need in a particular situation a value of a certain type T, I check if my value at hand can be converted into something of type T. If yes, I use the converted value instead, if not, then it’s a DomainError.

For this not to result in total chaos, a necessary condition for a type conversion to succeed should be that the conversion is reversible (at least in principle). Note that this is only a necessary condition, and you should really think twice before providing a type conversion. Often it makes more sense not to provide a type conversion, but just a conversion function which has to be invoked explicitly.

As an example, look at the conversion between integers and reals. It should be possible to convert integers that are not too large to a real; but if the integer is too large to be represented faithfully as a real number, the conversion should fail. Likewise, a real r for which r.round == r holds should be convertible to an integer. But the conversion should fail for those r with not(r.round == r).

This is a big issue, and adding automatic type conversions to Babel-17 changes the whole look and feel of the language. It will make it a lot easier for beginners to get friendly with the language; at the same time it will make it harder for a compiler (but not impossible, especially for a JIT) to generate fast code.

Automatic type conversions will be introduced in the upcoming Babel-17 v0.3, and further developed in Babel-17 v0.3.1.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: