Type inference failing on generic type with static member constraint

我是研究僧i 提交于 2019-12-22 05:23:22

问题


I have defined the following type (simplified from code):

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

When I build I get the warning :

warning FS0193: A type parameter is missing a constraint 'when ( ^a or ^?23604) : (static >member ( + ) : ^a * ^?23604 -> ^?23605)'

on the word "longer" in the last line. As far as I can see it should be able to infer that it is always adding two members of 'a. How can I get rid of this?


回答1:


This is an interesting question, using a let bound function instead of a static member doesn't seem to trigger the same warning. Presumably there are differences between the resolution of static type parameters in let bound and member functions.

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

You can then extend Polynomial with a + operator based on the let bound function above:

type Polynomial with
    static member inline (+) (x, y) = PolyAdder.addPoly x y

There is still no warning and the + operator works normally

let poly1 = [1; 2; 5; 6; 8] |> Polynomial
let poly2 = [7; 1; 2; 5;] |> Polynomial
let polyAdded = poly1 + poly2


来源:https://stackoverflow.com/questions/34436085/type-inference-failing-on-generic-type-with-static-member-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!