F# Type Inference
I am kind of new to F# so maybe my question is dumb. I wrote a program in F# that used generic types. Compiler determined the types not the way that I desired because I had a bug in the deepest function call that I had instantiated the type to a wrong type. This obviously resulted in type mismatch elsewhere that I had used the type as I had expected. I have to mention to find the root of problem I tried to explicitly enforce the higher level functions to use the types that I desired for the generic type. However the type mismatch was shown in those high-level functions not for the low level function were the type was instantiated. I think it's not very convenient way of determining types because usually it is much easier for programmers to determine the type on higher level functions and this explicit type assignment should result in type error in lower level function were the type has been determined. In my experience it seems automatic type determination of the compiler overrides the explicit type declaration. Am I understanding something wrong here?
Something like the code below:
type test<'a,'b>={Func:'a->'b; Arg:'a}
let C(a)=
a.Func(2)|>igno开发者_JAVA百科re
let B(a)=
C(a)
let A(a:test<int64,int64>)=
B(a) //<-----------------------the type mismatch is detected here
Having the error detected on such high level function call makes it difficult to find the root of the problem because now not only I have to look for the bugs regarding the value of variables but also the type determination bugs.
F#'s type inference is (fairly) strict top-to-bottom, left-to-right. See here for a discussion: Why is F#'s type inference so fickle?
You can check this by rearranging your code like this (just for demonstration):
type test<'a,'b>={Func:'a->'b; Arg:'a}
let rec B(a)=
C(a)
and A(a:test<int64,int64>)=
B(a)
and C(a)=
a.Func(2)|>ignore // type mismatch now here
The convenience level depends mostly on the concrete code, in my experience. But I have to admit that I too have sometimes been surprised by type mismatch error messages. It takes some time getting used to.
精彩评论