Monday, April 17, 2006

Compile-time type inference for ruby has its limit

I have been thinking about doing type inference at compiler time for ruby. Whiles lots of the cases can be handled in a straightforward way, type inference won't work in all situations.

One of the problems is, ruby supports multiple return types:

def f
if rand(2) == 1
return 1
return "hello"

In the above code, method 'f' will randomly return 1 (Fixnum) or "hello" (String). At compiler time there is no way for a compiler to know what type to return. All it can do is to insert meta data so that typing checking can be done at runtime.

And multiple return types is not uncommon in real code. For example, Ruby' s array or hash can hold objects of different types:

a = [1, 1.5, "hello"]

In the above code, Array 'a' contains three different types of objects: Fixnum, Float and String. And element reference("[]") is an example of method that has multiple return types.


Post a Comment

<< Home