How to define type extension for T [] in F #?

In C #, I can define an extension method for a generic array of type T as follows:

public static T GetOrDefault<T>(this T[] arr, int n) { if (arr.Length > n) { return arr[n]; } return default(T); } 

but for life I can’t understand how to do the same in F #! I tried type 'a array with , type array<'a> with and type 'a[] with , and the compiler was not happy with any of them.

Can someone tell me the right to do this in F #?

Of course, I can do this by eclipsing the Array module and adding a function for this is easy enough, but I really want to know how to do this as an extension method!

+15
arrays c # extension-methods f #
Aug 06 2018-12-21T00:
source share
2 answers

You need to write the type of the array using "backticks" - like this:

 type 'a ``[]`` with member x.GetOrDefault(n) = if x.Length > n then x.[n] else Unchecked.defaultof<'a> let arr = [|1; 2; 3|] arr.GetOrDefault(1) //2 arr.GetOrDefault(4) //0 

Change The syntax type ``[]``<'a> with ... also allowed. In the F # source (prim-types-prelude.fs) you can find the following definition:

 type ``[]``<'T> = (# "!0[]" #) 
+27
Aug 07 '12 at 15:38
source share
Good question. I can't figure out how to extend 'T[] , but you can take advantage of the fact that arrays implement IList<_> :
 type System.Collections.Generic.IList<'T> with member x.GetOrDefault(n) = if x.Count > n then x.[n] else Unchecked.defaultof<'T> let arr = [|1; 2; 3|] arr.GetOrDefault(1) //2 arr.GetOrDefault(4) //0 
+10
Aug 6 2018-12-12T00:
source share



All Articles