gpt4 book ai didi

f# - 是否可以要求静态解析的类型参数是泛型类型?

转载 作者:行者123 更新时间:2023-12-04 05:54:44 26 4
gpt4 key购买 nike

有层次结构

open FSharp.Data.UnitSystems.SI.UnitSymbols

type Vector2D<[<Measure>] 'u>(x: float<'u>, y: float<'u>) =
member val Abs =
let squared = float (x*x+y*y)
LanguagePrimitives.FloatWithMeasure<'u> (Math.Sqrt squared)

type R2D =
inherit Vector2D<m>(x, y)
member val X = x
member val Y = y

type V2D(vx, vy) =
inherit Vector2D<m/s>(vx, vy)
member val Vx = vx
member val Vy = vy

type A2D(ax, ay) =
inherit Vector2D<m/s^2>(ax, ay)
member val Ax = ax
member val Ay = ay

我想定义全局内联运算符 (+) (l:^v) (r:^v)其中 ^v需要继承自 Vector2D , 有一些计量单位 float<'u>并且 有两个参数类型为 float<'u> 的构造函数.

这可能吗?

最佳答案

您可以尝试定义 add 函数,然后将其分配给中缀运算符:

let add<[<Measure>]'u, 'v when 'v :> Vector2D<'u>> (l:^v) (r:^v) = l.Abs + r.Abs

let (+) left right = add left right

已编辑:这是您可以使用它的方式:在这种情况下,左右类型必须匹配

let left = R2D(1.0<m>,1.0<m>)
let right = R2D(2.0<m>,2.0<m>)
let result = left + right

或者你可以尝试不匹配类型,仍然单位必须匹配

let left:Vector2D<m> = R2D(1.0<m>,1.0<m>) :> Vector2D<m>
let right:Vector2D<m> = A2D2(2.0<m>,2.0<m>) :> Vector2D<m>
let result = left + right

关于f# - 是否可以要求静态解析的类型参数是泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56697839/

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