Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# generic struct constructor and error FS0670

Tags:

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.

like image 807
Ganfoss Avatar asked Nov 06 '18 15:11

Ganfoss


1 Answers

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
like image 171
Nikon the Third Avatar answered Nov 15 '22 06:11

Nikon the Third