Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type inference failing on generic type with static member constraint

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?

like image 820
MatthewJohnHeath Avatar asked Dec 23 '15 12:12

MatthewJohnHeath


1 Answers

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
like image 99
TheInnerLight Avatar answered Oct 18 '22 17:10

TheInnerLight