我想IEnumerable<KeyValuePair<DateTime, 'T>>
在我自己的类中实现并向该类添加数学运算符,以便运算符可以像任何数值类型的内联函数一样工作'T
- 自动添加约束.
我只是无法使下面的代码工作.在成员声明中,它既不能使用也不能使用'inline'关键字.
另外,如果我定义一个函数
let inline add l r = l + r
Run Code Online (Sandbox Code Playgroud)
在类型之前使用它而不是添加l.Value + r.Value,它也不起作用.
有人可以告诉我我做错了什么吗?
可能整个方法都是错误的,并且有另一种方法可以实现相同的目标吗?
namespace Test
open System
open System.Linq
open System.Collections.Generic
[<SerializableAttribute>]
type TimeSeries<'T>(dictionary : IDictionary<DateTime, 'T>) =
let internalList = new SortedList<DateTime, 'T>(dictionary)
interface IEnumerable<KeyValuePair<DateTime, 'T>> with
member this.GetEnumerator() = internalList.GetEnumerator()
member this.GetEnumerator() : Collections.IEnumerator
= internalList.GetEnumerator() :> Collections.IEnumerator
member private this.sl = internalList
static member inline (+) (left : TimeSeries<'T>, right : TimeSeries<'T>) =
let res =
query {
for l in left do
join r in right on
(l.Key = r.Key)
select (l.Key, l.Value + r.Value)
}
new TimeSeries<'T>(res |> dict)
Run Code Online (Sandbox Code Playgroud)
你的方法对我来说似乎是对的.您的代码无法编译的原因是因为F#类型推断推断出类型变量的静态约束(编译时),'T
它与用于类型定义的相同.
类型定义的泛型参数不能静态解析(没有"帽子"类型),但没有什么能阻止您定义使用这些编译时约束的函数或成员.
只要你的类型变量更改'T
到'U
静态成员(+)
定义,并会被罚款.
你仍然可以创建一个TimeSeries
不支持的类型的实例(+)
(即:),TimeSeries<obj>
但你无法使用(+)
那些实例,无论如何,如果你这样做,你会在编译时得到一个很好的错误信息.