views:

356

answers:

1

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?

+20  A: 

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

Brian
Great clarification. +1
Jose Basilio
I hope they make the type inference more robust. I've already hit a few cases where I had to reorder the methods in a class or I would get too generic type errors.
gradbot
For what its worth, this blog post and some of its comments have a useful explanation of some of F#'s strengths and weaknesses in its type checker: http://neilmitchell.blogspot.com/2008/12/f-from-haskell-perspective.html
Juliet