Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

f# - Overloading measure operator (*)

I am stuck attempting to overload the (*) operator for a Measure type.

What I would like to see is :

> let x = 1.0<i> * 1.0<i>;;

val x : float = -1.0

The following definition appears to do the trick :

> let inline (*) (v1 : float<i>) (v2 : float<i>) = float(-1) * float(v1) * float(v2);;

val inline ( * ) : float<i> -> float<i> -> float

Note that the product measure in this example correctly resolves to <1> as which happens for example when multiplying the imaginary unit of a complex number. Without this overloading definition the default product resolves to < i^2>.

But the overloading definition above has the nasty side effect that :

> let y = 1.0 * 1.0;;

let y = 1.0 * 1.0;;
--------^^^

stdin(11,9): error FS0001: This expression was expected to have type
float<i>    
but here has type
float

Apparently my overloading definition hides the (*) operator for the float type.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note that you are redefining the (*) operator rather than overloading it.

The trick to get it working is to write something using an intermediate type, like this:

type Mult = Mult with
    static member        ($) (Mult, v1: float<i>) = fun (v2: float<i>) -> 
                                 float(-1) * float(v1) * float(v2)
    static member inline ($) (Mult, v1      ) = fun v2 -> v1 * v2
    static member        ($) (Mult, v1: Mult) = fun () -> Mult //Dummy overload

let inline (*) v1 v2 = (Mult $ v1) v2

BTW funny way to use units of measure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...