Problems adding an extension to the DenseVector type

I am trying to add a method to the DenseVector class so that I can split the vector n times. The following does not seem to work, since type inference complains that the Vector type is incompatible with the DenseVector type:

open System open System.IO open Deedle open MathNet.Numerics open MathNet.Numerics.LinearAlgebra open MathNet.Numerics.LinearAlgebra.Double open MathNet.Numerics.Distributions [<Extension>] type DenseVector with member this.diffVector (v : DenseVector) (n : int) = let rec run (v : DenseVector) (n : int) = match n with | 0 -> v | _ -> run (v.[ 1 .. v.Count-1 ] - v.[ 0 .. (v.Count-1)-1 ]) (n - 1) run vn 

v.[ 0 .. (v.Count-1)-1 ] in the above question is causing problems. Why is it displayed as Vector, and not DenseVector - is that what is passed to the function? Also, my way to properly add an extension method?

+5
source share
1 answer

The reason for your problem is that the extension method that defines the GetSlice method for all Vector<'T> returns Vector<'T> not a DenseVector . Therefore, if you use slicing, which works by calling GetSlice , you will get Vector, and your code above will not work as expected.

I'm not sure how the inside of MathNet works, but you can just make your extension method work for all Vector<'T> with something like this:

 type Vector with member this.diffVector (v : Vector<'T>) (n : int) = let rec run (v : Vector<'T>) (n : int) = match n with | 0 -> v | _ -> run (v.[ 1 .. v.Count-1 ] - v.[ 0 .. (v.Count-1)-1 ]) (n - 1) run vn 

Alternatively, it may happen that you can simply dump something like this from Vector to DenseVector safely. This may or may not work:

 [<Extension>] type DenseVector with member this.diffVector (v : DenseVector) (n : int) = let rec run (v : DenseVector) (n : int) = match n with | 0 -> v | _ -> let v1 = v.[ 1 .. v.Count-1 ] :?> DenseVector let v2 = v.[ 0 .. (v.Count-1)-1 ] :?> DenseVector run (v1 - v2) (n - 1) run vn 
+3
source

Source: https://habr.com/ru/post/1257588/


All Articles