Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 776
kinghajj Avatar asked May 10 '09 05:05

kinghajj


1 Answers

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#.

like image 86
Brian Avatar answered Oct 28 '22 05:10

Brian