gpt4 book ai didi

f# - 为什么在这种情况下 F# 不能推断类型?

转载 作者:行者123 更新时间:2023-12-04 23:20:57 24 4
gpt4 key购买 nike

考虑以下示例代码,其中我有一个泛型类型和 2 个静态成员构造函数,它们创建了所述类型的专用实例。

type Cell<'T> = { slot: 'T }
with
static member CreateInt x : IntCell = { slot = x }
static member CreateString x : StringCell = { slot = x}
and IntCell = Cell<int>
and StringCell = Cell<string>

// Warnings on the next 2 lines
let x = Cell.CreateInt 123
let y = Cell.CreateString "testing"

我认为我有必要的类型注释,但 F# 给了我警告。例如:

Warning 2 The instantiation of the generic type 'Cell' is missing and can't be inferred from the arguments or return type of this member. Consider providing a type instantiation when accessing this type, e.g. 'Cell<_>'.

我怎样才能让警告消失?

最佳答案

正如@ildjarn 所暗示的,Cell是泛型类型,编译器想知道类型 'T调用静态成员时。

// Two ways to fix the compiler warning
let x = Cell<int>.CreateInt 123
let y = StringCell.CreateString "testing"

一种避免指定 'T 的方法是将创建功能移动到模块中。
type Cell<'T> = { slot: 'T }
type IntCell = Cell<int>
type StringCell = Cell<string>
module Cell =
let createInt x : IntCell = { slot = x }
let createString x : StringCell = { slot = x }

let x = Cell.createInt 123
let y = Cell.createString "testing"

但是,由于无论如何您都在函数名中指定了所需的类型,因此可能首选以下语法。
type Cell<'T> = { slot: 'T }
with
static member Create (x : 'T) = { slot = x }
type IntCell = Cell<int>
type StringCell = Cell<string>

let x = IntCell.Create 123
let y = StringCell.Create "testing"

// or simply
let z = Cell<float>.Create 1.0

感谢@Vandroiy 指出我的 Create 中缺少的类型约束。方法和他的回答,显示编译器如何推断 'T对于泛型 Cell何时可以通过调用的静态方法确定。

关于f# - 为什么在这种情况下 F# 不能推断类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093812/

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