Search code examples
f#type-inferencetype-annotation

F# type inference misses given information


If I declare this F# function:

let extractColumn col (grid : List<Map<string, string>>) =
    List.map (fun row -> row.[col]) grid

the compiler complains:

error FS0752: The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints

Adding a type annotation for the lambda's row parameter fixes it:

let extractColumn col (grid : List<Map<string, string>>) =
    List.map (fun (row : Map<string, string>) -> row.[col]) grid

Why can't it get the type of row from the extractColumn function's grid parameter?


Solution

  • F#'s type inference works from left to right and top to bottom.

    Type of grid isn't available in the List.map (fun row -> row.[col]) part.

    Using pipe operator |>:

    let extractColumn col (grid : Map<string, string> list) =
        grid |> List.map (fun row -> row.[col])
    

    makes your example work as expected.