如何在 F# 中为 T[] 定义类型扩展? [英] How to define a type extension for T[] in F#?
问题描述
在 C# 中,我可以为 T 类型的泛型数组定义一个扩展方法,如下所示:
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);
}
但对于我的生活,我不知道如何在 F# 中做同样的事情!我试过 type 'a array with
, type array<'a>with
和 type 'a[] with
编译器对它们中的任何一个都不满意.
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.
谁能告诉我在 F# 中这样做的权利是什么?
Can anyone tell me what's the right to do this in F#?
当然,我可以通过覆盖 Array 模块并为此轻松添加一个函数来做到这一点,但我真的很想知道如何将其作为扩展方法来实现!
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!
推荐答案
您必须使用反引号"来编写数组类型 - 像这样:
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
编辑:语法type ``[]``<'a>with ...
似乎也被允许.在 F# 源代码 (prim-types-prelude.fs) 中,您可以找到以下定义:
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[]" #)
这篇关于如何在 F# 中为 T[] 定义类型扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!