.net - F# Type inference on Math.Max -
why won't compiler pick correct version of overloaded method if has inferred types of input parameters.
in example why can't pick correct math.max use when type has correctly inferred on elements being compared:
let listmax = list.map2 (fun l r -> math.max(l,r)) [2;4] [5;3] //compile error let listmax2 = list.map2 (fun (l:int) r -> math.max(l,r)) [2;4] [5;3] //no compile error
of course can use max function in case, there plenty of other methods don't have native equivalent.
as @gos correctly points out, using pipeline operator helps in case. reason type inference works left right - so, if use pipeline operator, knows 1 of inputs list of integers and, based on that, picks right overload of math.max
.
the compiler needs know type when overload resolution or when want invoke member on object (e.g. if wanted l.foo()
inside map function) - because in case, needs know type is.
f# defines own versions of basic math functions work better type inference. can replace math.max
max
functions (which can nicely pass directly map2
):
list.map2 max [2;4] [5;3]
this works better, because f# not need perform overload resolution (the function not overloaded). keeps track of special generic constraint satisfied , resolved later.
Comments
Post a Comment