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
?
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#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With