Why can't F#'s type inference handle this?

送分小仙女□ 提交于 2019-12-17 19:35:37

问题


I have a sequence of FileInfo, but I only care about their string names, so I want a sequence of string. At first I tried something like this:

Seq.map (fun fi -> fi.Name) fis

But for some reason, F#'s type inference isn't good enough to allow this, and made me explicitly give a type to "fi":

Seq.map (fun (fi : FileInfo) -> fi.Name) fis

Why is this annotation required? If it is known that fis : seq<FileInfo> and that Seq.map : ('a -> 'b) -> seq<'a> -> seq<'b>, then shouldn't it infer that the type of the lambda expression is FileInfo -> 'b, and then, from fi.Name : string, further infer that its type is FileInfo -> string?


回答1:


Type inference works left-to-right. This is where the pipeline operator is useful; if you already know the type of 'fis', then write it as

fis |> Seq.map (fun fi -> fi.Name)

and the inference works for you.

(In general, expressions of the form

o.Property
o.Method args

require the type of 'o' to be known a priori; for most other expressions, when a type is not pinned down the inference system can 'float a constraint' along that can be solved later, but for these cases, there are no constraints of the form 'all types with a property named P' or 'all types with a method named M' (like duck typing) that can be postponed and solved later. So you need that info now, or inference fails immediately.)

See also an overview of type inference in F#.



来源:https://stackoverflow.com/questions/844733/why-cant-fs-type-inference-handle-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!