In C#, I can define an extension method for a generic array of type T like this:
public static T GetOrDefault<T>(this T[] arr, int n)
{
if (arr.Length > n)
{
return arr[n];
}
return default(T);
}
but for the life of me I can't figure out how to do the same in F#! I tried type 'a array with
, type array<'a> with
and type 'a[] with
and the compiler wasn't happy with any of them.
Can anyone tell me what's the right to do this in F#?
Sure, I can do this by overshadowing the Array module and add a function for that easily enough, but I really want to know how to do it as an extension method!
Good question. I can't figure out how to extend
'T[]
but you can take advantage of the fact that arrays implementIList<_>
to do:You have to write the array type using 'backtick marks' - like this:
Edit: The syntax
type ``[]``<'a> with ...
seems to be allowed as well. In the F# source (prim-types-prelude.fs) you can find the following definition: