【问题标题】:F# type inference misses given informationF# 类型推断遗漏给定信息
【发布时间】:2013-06-27 20:50:57
【问题描述】:

如果我声明这个 F# 函数:

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

编译器抱怨:

错误 FS0752:运算符 'expr.[idx]' 已根据此程序点之前的信息用于不确定类型的对象。考虑添加更多类型约束

为 lambda 的 row 参数添加类型注释修复它:

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

为什么不能从extractColumn函数的grid参数中得到row的类型?

【问题讨论】:

    标签: f# type-inference type-annotation


    【解决方案1】:

    F# 的类型推断从左到右和从上到下工作。

    grid 的类型在 List.map (fun row -&gt; row.[col]) 部分中不可用。

    使用管道运算符|&gt;:

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

    使您的示例按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多