War*_*ung 2 f# type-inference type-annotation
如果我声明这个F#函数:
let extractColumn col (grid : List<Map<string, string>>) =
List.map (fun row -> row.[col]) grid
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
错误FS0752:运算符'expr.[idx]'已根据此程序点之前的信息用于不确定类型的对象.考虑添加其他类型约束
为lambda row参数添加类型注释会修复它:
let extractColumn col (grid : List<Map<string, string>>) =
List.map (fun (row : Map<string, string>) -> row.[col]) grid
Run Code Online (Sandbox Code Playgroud)
为什么不能row从extractColumn函数的grid参数中获取类型?
F#的类型推断从左到右,从上到下.
零件中grid没有类型List.map (fun row -> row.[col]).
使用管道操作员|>:
let extractColumn col (grid : Map<string, string> list) =
grid |> List.map (fun row -> row.[col])
Run Code Online (Sandbox Code Playgroud)
使您的示例按预期工作.