【问题标题】:Duck typing with type provider instances [duplicate]使用类型提供程序实例进行鸭子打字[重复]
【发布时间】:2015-06-16 15:48:08
【问题描述】:

我正在编写一个 F# 脚本来操作数据库中的表。所有表都有一个Guid Id 属性。我想在几个地方使用鸭子类型来引用这个 ID。

以这个函数为例:

let inline getAllIds<'a when 'a : (member Id : Guid with get)
                        and 'a : not struct> (table : Table<'a>) =
    table |> Seq.map (fun x -> x.Id)

我曾希望 when 'a : (member Id : Guid with get) 约束允许我在表记录上使用 Id 属性,但我收到类型推断错误(“可能需要类型注释”等)。

此外,如果我尝试将没有Guid Id 属性的表传递给函数,它会正确地抱怨它不支持运算符get_Id。这似乎向我表明我的语法是正确的,但可能在某处需要额外的约束。我想做的事可能吗?

(我知道我可以将一个函数传递给这个函数来检索 ID...但是这有什么乐趣呢?!)

【问题讨论】:

  • "将一个 function 传递到这个 function" 找到它。
  • ...叹息,有一个 +1 :p

标签: f# type-providers duck-typing


【解决方案1】:

我会坚持认为这是重复的,但这里是您需要开始的确切代码:

let inline getAllIds< ^a when ^a : not struct> (table : Table< ^a>) =
    table |> Seq.map (fun x -> (^a : (member Id : Guid with get) x))

或者,可以使用以下语法:

let inline getAllIds< ^a when ^a : not struct> (table : Table< ^a>) =
    table |> Seq.map (fun x -> (^a : (member get_Id : unit -> Guid) x))

IIRC,使用 3.0 之前的 F# 编译器时,后一种语法是必需的

【讨论】:

  • 谢谢!没错,这是您在评论中链接的问题的重复问题
猜你喜欢
  • 2017-10-24
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 2020-09-30
  • 2016-08-20
  • 1970-01-01
相关资源
最近更新 更多