RomnieEE
RomnieEE

Reputation: 610

F#, small type inference / annotation error

This line in F# gives the error that a type annotation may be needed, at "x.Day".

  let daysList = List.map (fun x -> x.Day) datesList

But intellisense shows that x is of type DateTime (at "fun x"). And that datesList is of type DateTime list. So I'm perplexed as to why I have to declare the type of x like so and then everything works:

  let daysList = List.map (fun (x:System.DateTime) -> x.Day) datesList

Upvotes: 2

Views: 76

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233197

The F# compiler generally prefers inferring types from left to right, so if you write it using the pipe operator, it works, assuming that datesList is a DateTime list:

let daysList = datesList |> List.map (fun x -> x.Day)

Why, then, can IntelliSense determine that x is a DateTime? Beats me, but in my experience it's fairly common that IntelliSense sometimes disagrees with the compiler.

BTW, that left to right rule doesn't always seem to be strict, either. I often have to experiment a bit before I get everything right.

Upvotes: 5

Related Questions