具有 静态解析类型参数 的内联函数可能需要具有特定名称和签名的成员。 F# 11.2 允许范围内扩展成员满足该要求,即使类型来自另一个程序集也是如此。
使用此功能可将泛型算法与特定类型的适配器分开。 无需包装这些类型或向其添加名义接口。
Note
在 .NET 11.0.100 SDK 中,启用<LangVersion>preview</LangVersion>编译器解析扩展的位置。 请参阅计划的功能带的 F# 11.2 语言设置 。 路径和映射示例使用 F# 11.0 库和预览使用者;请参阅 编译库和使用者。
调整共享算法的属性
以下应用程序代码度量由两种现有框架类型表示的路径。 这两个路径的长度 8为:
open System.Numerics
open Structural.Adapters
open Structural.Algorithms
let complexRoute =
[ Complex(0.0, 0.0); Complex(3.0, 4.0); Complex(6.0, 4.0) ]
let vectorRoute =
[ Vector2(0.0f, 0.0f); Vector2(3.0f, 4.0f); Vector2(6.0f, 4.0f) ]
printn (pathLength complexRoute) // 8
printn (pathLength vectorRoute) // 8
库源定义Structural.Adapters和 Structural.Algorithms。 适配器针对具有不同本机 API 的类型公开相同的坐标属性:
type System.Numerics.Complex with
member point.Coordinates = point.Real, point.Imaginary
type System.Numerics.Vector2 with
member point.Coordinates = float point.X, float point.Y
该算法要求 Coordinates 返回一对浮点值的属性:
let inline coordinates (point: ^Point) : float * float =
(^Point : (member Coordinates: float * float) point)
let inline pathLength (points: ^Point list) =
points
|> List.pairwise
|> List.sumBy (fun (a, b) ->
let ax, ay = coordinates a
let bx, by = coordinates b
let dx, dy = bx - ax, by - ay
sqrt (dx * dx + dy * dy))
在每个具体调用中,编译器选择一个名为 Coordinates 约束 见证的成员。 内联算法接受内部属性或扩展属性;空路径和单点路径长度为零。
跨集合类型共享操作
扩展约束还支持静态成员。 库的 Structural.Adapters 模块使用现有 List.map 函数和 Option.map 函数定义适配器:
type List<'T> with
static member Map(source: 'T list, mapping: 'T -> 'U) : 'U list =
List.map mapping source
type Option<'T> with
static member Map(source: 'T option, mapping: 'T -> 'U) : 'U option =
Option.map mapping source
在库的 Structural.Algorithms 模块中,在完整的输入类型上请求 Map 成员:
let inline map (mapping: 'T -> 'U) (source: ^Input) : ^Output =
(^Input :
(static member Map: ^Input * ('T -> 'U) -> ^Output)
(source, mapping))
然后,应用程序可以共享转换、更改元素类型,并在嵌套集合上撰写映射:
let inline cleanNames values =
map (fun (name: string) -> name.Trim().ToUpperInvariant()) values
let batch: string list = cleanNames [ " Ada "; " grace " ]
let optional: string option = cleanNames (Some " linus ")
let missing: string option = cleanNames (None: string option)
let lengths: int list = map String.length batch
let nested: int option list = map (map String.length) [ Some "abc"; None ]
printfn "%A; %A; %A" batch optional missing
printfn "%A; %A" lengths nested
// ["ADA"; "GRACE"]; Some "LINUS"; None
// [3; 5]; [Some 3; None]
编译器检查成员名称和类型,而不是接口或映射法。 这不是更高级别的多态性:没有参数表示容器构造函数,例如 F<_>。
运算符扩展
运算符可以使用同一机制。 例如,为列表和选项定义映射运算符:
type List<'T> with
static member (|>>) (source: 'T list, mapping: 'T -> 'U) =
List.map mapping source
type Option<'T> with
static member (|>>) (source: 'T option, mapping: 'T -> 'U) =
Option.map mapping source
let inline (|>>) (source: ^Input) (mapping: 'T -> 'U) : ^Output =
(^Input :
(static member (|>>): ^Input * ('T -> 'U) -> ^Output)
(source, mapping))
使用者打开 StructuralOperators 并使用运算符:
open StructuralOperators
let incremented: int list = [1; 2; 3] |>> ((+) 10)
let length: int option = Some "hello" |>> String.length
// [11; 12; 13] and Some 5
内置基元运算符解决方案保留匹配类型的优先级。 扩展不提供任意混合数字加宽或替换所有内置运算符。
F# 11.0 模式可以使用 FS1215 接受普通扩展运算符声明,但不能将其用作 SRTP 解决方案。 运算符项目使用预览版。
元组运算符和上下文
观察的集合和一对独立累积的结果可以参与同一组合协议。 以下使用者在打开库的适配器后定义其泛型算法:
open Composition.Adapters
open Composition.Algorithms
let inline combineAll (batches: ^T list) : ^T =
List.reduce (++) batches
let observations = combineAll [["temperature"]; ["pressure"; "humidity"]]
let summary = combineAll [(2, ["temperature"]); (3, ["pressure"; "humidity"])]
printfn "%A" observations
printfn "%A" summary
// ["temperature"; "pressure"; "humidity"]
// (5, ["temperature"; "pressure"; "humidity"])
这些库扩展为运算符提供整数、列表和对的含义:
type System.Int32 with
static member (++) (left: int, right: int) = left + right
type List<'T> with
static member (++) (left: 'T list, right: 'T list) = left @ right
type ('T1 * 'T2) with
static member inline (++) ((a, b), (c, d)) = (a ++ c, b ++ d)
combineAll 需要非空列表,因为它使用 List.reduce。 该操作保留列表顺序;编译器不强制实施关联性或提供空输入的标识。
本机标头 type ('T1 * 'T2) with 和 type struct ('T1 * 'T2) with 扩展 CLR 引用和值元组。 两者都是 F# 11.2 功能,支持 2 到 7 个元素:较大的标头生成 FS3915。
元组还可以将上下文与值一起携带。 以下运算符在应用上下文函数时追加尾随:
let priced =
(["catalogue price"], fun units -> decimal units * 12m)
<*> (["validated quantity"], 3)
printfn "%A" priced
// (["catalogue price"; "validated quantity"], 36M)
type ('Context * 'Value) with
static member inline (<*>) ((before, mapping), (after, value)) =
(before ++ after, mapping value)
type struct ('Context * 'Value) with
static member inline (<*>) (struct (before, mapping), struct (after, value)) =
struct (before ++ after, mapping value)
不支持元组点实例调用和本机函数类型标头,例如 type ('a -> 'b) with 。
合成库和使用者都使用预览版。 保留在 combineAll 使用者中:导出该减少可以为元组 ++生成 FS0193。 单独的路径和映射示例导出其算法。
返回定向构造
对于将纯值引入容器的操作,输出类型可以标识应构造它的成员:
type List<'T> with
static member Return(value: 'T) : 'T list = [value]
type Option<'T> with
static member Return(value: 'T) : 'T option = Some value
let inline singleton (value: 'T) : ^Output =
(^Output : (static member Return: 'T -> ^Output) value)
let oneBatch: string list = singleton "ready"
let oneOptional: string option = singleton "ready"
// ["ready"] and Some "ready"
使用者的结果注释选择输出类型的 Return 扩展。 仅输入就不能选择容器。
每个容器都提供自己的成员。 对于单个类型的仅返回重载,请使用单独的 AllowOverloadOnReturnType 属性。
编译库和使用者
语言设置适用于每个项目,而不是通过引用传递。 以下矩阵使用 .NET 11.0.100 SDK 的 F# 11.2 功能设置:
| 库实现 | 使用者使用 | 预览要求 |
|---|---|---|
| 声明本机元组扩展标头。 | 解析其扩展运算符。 | 两者都需要预览;新的标头语法本身为预览版。 |
| 定义普通扩展并导出未解析的内联成员约束。 | 提供扩展可解决该约束的具体类型。 | 使用者需要预览版。 该库可以使用 F# 11.0。 |
| 在内部解决扩展约束,并公开普通或已解析的内联 API。 | 在没有进一步扩展解析的情况下调用该 API。 | 库需要预览;使用者可以使用 F# 11.0。 |
| 解决使用者也通过扩展解析的扩展和导出约束。 | 解析剩余约束。 | 两者都需要预览版。 |
路径和映射 库 使用 11.0;其 使用者 使用 preview。 在使用者目录中,使用支持的 F# 11 SDK 运行 dotnet run 。
跨程序集的扩展范围
在定义依赖内联函数之前,请使用公共扩展并打开其模块。 对于导入的未解析约束,还可以在使用者中打开适配器;生成者的 open 声明不会转移。 已解析的 API 不需要使用者重新打开其适配器。
推理和签名
F# 11.2 分辨率推迟了 F# 11.0 模式先前做出的一些选择。 请考虑使用 DateTime 接收方定义的内联帮助程序:
let inline shift (date: System.DateTime) offset = date + offset
在 F# 11.0 模式下,此形式可以推断 DateTime -> TimeSpan -> DateTime。 启用 F# 11.2 扩展解析后,它可以保留约束。(DateTime or ^Offset) : (static member (+) : DateTime * ^Offset -> ^Result) 然后,使用者可以为不同的偏移类型选择公共范围扩展。
使用者无法恢复 F# 11.0 库中丢失的通用性。 检查导出的签名;生成者可能还需要启用 F# 11.2 推理。
预览限制和故障排除
- 对于 FS0001 或 FS0193,请检查语言设置、公开可见性和适配器范围。
- 如果以后的生成者文件解析路径示例
Complex,则代码生成可能会失败,并显示 FS0971Undefined value 'get_Coordinates'。 请保留该分辨率及其定义或单独的使用者。 - 竞争适配器可以使成员选择不明确。