f# - 如何在同一个函数中编写泛型类型和鸭子类型?
问题描述
我怎么能这样写(它有编译错误)?
module T =
let inline (|Id|) x =
fun () -> (^a : (member Id: string) x)
let inline id (Id f) = f()
let inline test<'a> param =
let aT = typeof<'a>.Name
let idStr = id param
sprintf "%s %s" aT idStr
type C =
{ Name: string }
with
member __.Id = "1"
let c = { Name = "abc" }
let b = test<int> c
我希望test
函数接收泛型类型'a
,因为我想使用 in 类型let aT = typeof<'a>.Name
,并且它也可以接收类型 of param
(静态解析的),因为我想使用 in 类型let idStr = id param
。
解决方案
老实说,我不确定为什么会发生这种情况。也许是因为您需要明确指定所有类型参数,如果您指定一个?正如我所说,我不知道。但是,向函数添加另一个类型参数test
似乎可以解决问题:
module T =
let inline (|Id|) x =
fun () -> (^a : (member Id: string) x)
let inline id (Id f) = f()
let inline test<'a, ^b when ^b : (member Id: string)> (param: ^b) =
let aT = typeof<'a>.Name
let idStr = id param
sprintf "%s %s" aT idStr
type C =
{ Name: string }
with
member __.Id = "1"
let c = { Name = "abc" }
let b = test<int, _> c
推荐阅读
- react-native - 博览会更新后无法连接到本地主机
- java - 更改 Java Eclipse 代码中的输出颜色
- sql-server - '<' 和 '>' 等比较运算符如何处理字符串值?
- r - 在 R 中展开/估算时间序列
- vue.js - 将数据传递给 vue.js 方法
- seo - 在 AEM 中,我想添加
标签内的标签。架构内的多字段选项 - php - PHP MySQL - 为什么存储过程调用在 PHP 代码中意外结束
- list - python重新排序列表元素并转换为set
- matlab - 如何从日期时间中提取特定的时间范围?
- c++ - 如何让 UDP 套接字丢弃最早排队的数据包而不是新的传入数据包?