(i * x.Leng-6ren">
gpt4 book ai didi

f# - 为什么这个示例中存在类型推断错误

转载 作者:行者123 更新时间:2023-12-04 22:46:36 25 4
gpt4 key购买 nike

我在这段代码中收到“根据此程序点之前的信息查找不确定类型的对象”错误:

let a = [|"a"; "bb"|]
let n = Array.mapi (fun i x -> (i * x.Length)) a

它有什么问题?当我将光标悬停在 x 上方时,Visual Studio F# Interactive 正确地将 x 的类型显示为字符串。为什么我必须写:

let a = [|"a"; "bb"|]
let n = Array.mapi (fun i (x:string) -> (i * x.Length)) a

编译成功?

最佳答案

类型检查器从左到右工作。由于这个原因,编译器没有足够的信息来推断 x 的正确类型。 .

克服这个问题最简单的方法是放置a一开始:

let n = a |> Array.mapi (fun i x -> (i * x.Length))

编译器会知道 a类型为 string [] ,因此,x属于 string .

另一种选择是使用静态函数:

let n = Array.mapi (fun i x -> (i * String.length x)) a

String.length需要 string ,等等 string成为 x 的推断类型.

关于f# - 为什么这个示例中存在类型推断错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com