Begtostudy
Begtostudy

Reputation: 1424

How to do Operator Overloading?

I did this :

let (-) (m:float[]) (n:float[])=  [| for i = 0 to Array.length m - 1 do yield m.[i]-n.[i] |]

But, why this is wrong?!

let y=1.0-0.0

That is ok before!

Error   1   This expression was expected to have type     float []     but here has type     float      E:\MyDocuments\Visual Studio 2010\Projects\curve intersection\newton\Module1.fs 28  7   newton
Error   2   This expression was expected to have type     float []     but here has type     float      E:\MyDocuments\Visual Studio 2010\Projects\curve intersection\newton\Module1.fs 28  11  newton

I think (m:float[]) (n:float[]) is set the parameters type , why 1.0-0.0, floatfloat, not go to use (-) floatfloat->float???

Upvotes: 1

Views: 205

Answers (2)

Brian
Brian

Reputation: 118865

You completely redefined the - operator.

If you want to augment one of your own types to work with -, you can do that (the builtin operator definitions will pick up members on a type). But I don't think there's any way to define existing operators on builtin/existing types that doesn't completely shadow the builtin operator definition.

You can either use a local let binding to temporarily shadow - to work on float arrays, or you can define a new operator instead. Examples:

// locally shadow
let f() =
    let (-) (a:float[]) (b:float[]) = ...
    // use (-) on arrays for a moment
// use (-) as normal

and

// new operator
let (-@) (a:float[]) (b:float[]) = ...
[|1.0|] -@ [|2.0|]  // my new op
1.0 - 2.0           // minus as normal

Upvotes: 7

JaredPar
JaredPar

Reputation: 754745

You added an operator overload for the type float[]. In the sample code though you are trying to subject 2 float values which doesn't work. Try the following

let y = [|1.0|] - [|0.0|]

The [| ... |] syntax is used to create an array of values. In the above case it creates two float[] each with a single float value.

Upvotes: 1

Related Questions