Consider the following code:
type Base(x : float) =
member this.x = x
static member (~-) (a : #Base) = Base(-a.x)
static member Cos (a : #Base) = Base(cos a.x)
type Inherited(x : float) =
inherit Base(x)
let aBase = Base(5.0)
let aInherited = Inherited(5.0)
-aBase // OK, returns Base(-5.0)
-(aInherited :> Base) // OK, returns Base(-5.0)
-aInherited // not OK
The last line produces an error:
error FS0001: This expression was expected to have type
Inherited
but here has type
Base
Same with cos aInherited
: it gives the same error, but -(aInherited :> Base)
and cos (aInherited :> Base)
do work.
The error message suggests that these functions want the return type of -
or cos
to be the same as the argument type. This seems like an overly harsh requirement.
- For classes that inherit from a base type that defines the operators, this is not possible unless you redefine every operator.
- If those classes reside in an external library over which you don't have control, your options are even more limited.
Is there a way around this? In the F# source code, the cos
function is defined in prim-types.fs
.