Type of the Item property in F#
Consider the interface:
type IVector =
abstract Item : int -> float
Now, let us define the class:
type DenseVector(size : int) =
let mutable data = Array.zeroCreate size
interface IVector with
member this.Item with get n = data.[n]
What about supply a method to mutate the n-th entry of the dense vector? Then, it would be nice to modify the above code as:
type DenseVector(size : int) =
let mutable data = Array.zeroCreate size
interface IVector with
member this.Item with get n = data.[n]
and set n value = data.[n] <- value
However, I get the following error because of the signature of the abstract method Item
in the IVector
interface:
No abstract property was found that corresponds to this override.
So, what should be the signature o开发者_运维知识库f Item
in IVector
?
type IVector =
abstract Item : int -> float with get, set
You can implement DenseVector without changing the original interface while also providing a setter like this:
type IVector =
abstract Item: int -> float with get
type DenseVector(size : int) =
let data = Array.zeroCreate size
interface IVector with
member this.Item with get i = data.[i]
member this.Item
with get i = (this :> IVector).[i]
and set i value = data.[i] <- value
精彩评论