Ganfoss
Ganfoss

Reputation: 77

F# generic struct constructor and error FS0670

I have found some issues about error FS0670 (This code is not sufficiently generic. ...) inside StackOverflow, but none of the proposed solution works fine with my issue (I'm a beginner, perhaps I miss in some concepts of F#).

I have the following generic structure that I would like to works only with primitive types only (i.e. int16/32/64 and single/float/decimal).

[<Struct>]
type Vector2D<'T when 'T : struct and 'T:(static member get_One: unit -> 'T) and 'T:(static member get_Zero: unit -> 'T) > = 

    val x : 'T
    val y : 'T

    new( xp: 'T, yp: 'T ) = { x = xp; y = yp }

But with the new constructor, I get the mentioned error FS0670.

Does somebody knows a possible solution? Many thanks in advance.

Upvotes: 5

Views: 468

Answers (1)

Nikon the Third
Nikon the Third

Reputation: 2831

You cannot have statically resolved type parameters on structs.

They are only valid for inline functions. What you are trying to do (constrain a type parameter to require specific methods) is not possible in this case.

The closest you can get is to drop the member constraints from the struct and create inline functions that handle the struct for you:

[<Struct>]
type Vector2D<'T when 'T : struct> =
    val x : 'T
    val y : 'T

    new( xp: 'T, yp: 'T ) = { x = xp; y = yp }

let inline create< ^T when ^T : struct and ^T:(static member get_One: unit -> ^T) and ^T:(static member get_Zero: unit -> ^T)> (x : ^T) (y : ^T) =
    Vector2D< ^T> (x, y)


create 2.0 3.0 |> ignore
create 4   5   |> ignore

Upvotes: 4

Related Questions