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

拈花ヽ惹草 提交于 2019-11-28 09:50:35

You have to write the array type using 'backtick marks' - 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

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:

type ``[]``<'T> = (# "!0[]" #)

Good question. I can't figure out how to extend 'T[] but you can take advantage of the fact that arrays implement IList<_> to do:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!