Hacker News new | ask | show | jobs
by ReleaseCandidat 1055 days ago
> It looks simple but in a typed language it's actually somewhat tricky.

But that example looks about as simple as it can be, so I clearly must miss something.

> The compiler needs to infer that the 1 is a float type, 2 is a byte, and compile it appropriately.

And I don't understand _why_ it has to infer anything, as the type is explicitly declared. I mean, there are 2 possibilities: * 1 is both a valid integer and a float literal => Nim needs the type declaration on the left to unify the type (from "integer or float" or "numeric" or whatever the type checker inferred) to `float`. * 1 is not a valid float literal (but an integer) => the type is not inferred, but implicitly converted to `float`. In both cases the solution does not involve inference?

2 comments

You're completely right, but believe it or not Nim 1.6 actually doesn't manage to connect the dots between `1` and it being a possible `float`, `int64`, etc.. Even if you wanted a different size integer literal you'd have to say, for example, `42'int64`. You would be forgiven for asking how the language has purity checks for functions (`func` vs. `proc`) but somehow does not have this fairly elementary implicit type conversion (where Odin manages to even say `1.0` is a valid int value, for example, but won't permit anything that is not safely representable as a conversion).
> And I don't understand _why_ it has to infer anything, as the type is explicitly declared.

The seq declaration doesn’t need to be inferred. However the right side does need to be inferred from the declaration.

> I mean, there are 2 possibilities: * 1 is both a valid integer and a float literal => Nim needs the type declaration on the left to unify the type

Yep, `1` is an ambiguous number literal. So the compiler needs to back the info from the type into the assignment expression. Not super hard to do for simple cases, but it can become expensive for complex types.