F # Statically permitted element types of type

I want to implement IEnumerable<KeyValuePair<DateTime, 'T>> in my class and add mathematical operators to this class so that the operators can work as a built-in function for any numeric types 'T - automatically add constraints.

I just can't make the following code snippet. It does not work with or without the keyword "inline" in a member’s ad.

Also, if I define a function

 let inline add lr = l + r 

before the type and use it instead of adding l.Value + r.Value, it also does not work.

Can someone please show me what I'm doing wrong?

Probably the whole approach is wrong, and is there a way to achieve the same goal in a different way?

 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) 
+8
type-inference f #
source share
1 answer

Your approach seems right to me. The reason your code does not compile is because type F # output infers a static constraint (compile time) on a variable of type 'T , which is used to determine the type.

The generic type parameter cannot be statically resolved (no hat types), but nothing prevents you from defining a function or element that uses these compilation time restrictions.

Just change a variable like 'T to 'U in the definition of the static member (+) , and everything will be fine.

However, you will be allowed to create an instance of a TimeSeries type that does not support (+) (i.e.: TimeSeries<obj> ), but you cannot use (+) for these instances, anyway, if you do, You will get a good error message at compile time.

+6
source share

All Articles