我定义了以下类型(从代码简化):
type Polynomial<'a when 'a :(static member public Zero : 'a)
and 'a: (static member (+): 'a*'a -> 'a)
and 'a : (static member (*): 'a*'a -> 'a) > =
| Polynomial of 'a list
with
static member inline (+) (x: Polynomial<'a> , y : Polynomial<'a>) : Polynomial<'a>=
match x,y with
|Polynomial xlist, Polynomial ylist ->
let longer, shorter =
if xlist.Length> ylist.Length then xlist, ylist
else ylist, xlist
let shorterExtended = List.append shorter (List.init (longer.Length - shorter.Length) (fun _ -> LanguagePrimitives.GenericZero<'a>))
List.map2 (+) longer shorterExtended |> Polynomial
当我建立时,我得到警告:
警告FS0193:类型参数缺少约束'当(^ a或^?23604):(静态>成员(+):^ a * ^?23604-> ^?23605)'
最后一行中的“更长”一词。据我所知,它应该能够推断出它总是在添加两个'a成员。我该如何摆脱呢?
这是一个有趣的问题,使用let
绑定函数代替静态成员似乎不会触发相同的警告。可能在let绑定函数和成员函数中,静态类型参数的解析之间存在差异。
module PolyAdder =
let inline addPoly x y =
match x,y with
|Polynomial xlist, Polynomial ylist ->
let (longer : ^a list), (shorter : ^a list) =
if xlist.Length > ylist.Length then xlist, ylist
else ylist, xlist
let shorterExtended : ^a list = shorter @ (List.init (longer.Length - shorter.Length) (fun _ -> LanguagePrimitives.GenericZero< ^a >))
// no warning here!
List.map2 (+) longer shorterExtended |> Polynomial
然后Polynomial
,您可以根据上面的let绑定函数使用+运算符进行扩展:
type Polynomial with
static member inline (+) (x, y) = PolyAdder.addPoly x y
仍然没有警告,+运算符正常工作
let poly1 = [1; 2; 5; 6; 8] |> Polynomial
let poly2 = [7; 1; 2; 5;] |> Polynomial
let polyAdded = poly1 + poly2
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句