How do I implement basic type inference, nothing fancy just for inferring if the given value is an integer, double, or float. For instance, if I had a token for each type WHOLE_NUMBER, FLOAT_NUMBER, DOUBLE_NUMBER, and I had an expression like 4f + 2 + 5f, how would I deduce what type that is? My current idea was to just use the first type as the inferred type, so that would be a float. However, this doesn't work in most cases. What would I have to do?
2 Answers
My current idea was to just use the first type as the inferred type
No. Usually, the expression's type is that of its "widest" term. If it contains a double, then it's a double. If not but contains a float, then it's a float. If it has only integers then it is integer...
This applies to each parenthesized sub-expression. Unless you make an explicit cast.
In your example above, there are 2 floats and an int, so it is a float. The compiler should warn you though, as any implicit conversion it has to make may result in a loss of data.
The way I would do it would be to cast into the most "accurate" or specific type. For example, if you add a bunch of integers together, the result can always be represented by an integer. The moment a floating-point value is included in the expression, the result must be a float, as the result of the calculation might be fractional due to the floating-point term in the addition.
Similarly, if there are any doubles in the expression, the answer must be a double, as down-casting to a float might result in loss of precision. So, the steps required to infer the type are:
- Does the expression contain any
doubles? If so, the result is adouble- cast any integers orfloats todoubleas appropriate. If not... - Does the expression contain any
floats? If so, the result is afloat- case any integers tofloatas appropriate. If not... - The result is an integer, as the expression is entirely in terms of integers.
Different programming languages handle these sorts of situations differently, and it might be appropriate to add compiler warnings in situations where these automatic casts could cause a precision error. In general, make sure the behaviour of your compiler/interpreter is well-defined and predictable, such that any developer needing alternate behaviour can (and knows when to) use explicit casts if they need to preserve the accuracy of a calculation.
_Genericprogramming (which, I think, would allow you to write code where compiler would infer the type at compile time)? Please clarify! - hyde