F# does not support implicit conversions. I understand that this is a feature, but I don't understand why implicit conversions are forbidden even when no information would be lost. For example:
sqrt 4 // Won't compile.
I don't see a problem开发者_JS百科 implicitly converting the int
4 to a float
, which is what sqrt
requires.
Can anyone shed light on this?
Because its type checker almost depends on classical strong type-reconstruction. You example requires the coercion of types which is possible through implicit casts or a weak type system, but these aren't allowed in this kind of type inference.
Since F# comes from OCaml it has a type reconstruction that tries to guarantee correctness of your program by being extremely pedantic: the algorithm tries to unify the whole types of your program to a good typing and this cannot be done if a weak type rule allows to consider an integer like a float.
See also
http://lorgonblog.wordpress.com/2009/10/25/overview-of-type-inference-in-f/
which describes how overloading interacts badly with type inference. Implicit conversions cause many of the same problems as overloading, and also interact poorly with error diagnostics.
In addition to the above answers, type conversions between integer and float are not actually free in computational terms; the compiler is not doing you a favour by "hiding" them from you if your goal is to write high-performance code. This is one of the things I like about OCaml and F#: even tho' they are very high level, you still need to be aware of exactly what computation you are doing.
精彩评论