F # Member Constraints on Tuples

I usually have an β€œoh yes” moment writing F # when I realize that I need an extra value somewhere. This is usually easy to do by adding a different value to the transferred tuple. However, this means that the various maps are / sorts / collects / etc. an update is required, and in particular, the fst / snd functions only work with tuples of length 2.

This is not a huge problem, but it is annoying enough during the search development, which, although I would write an assistant to ease the annoyance:

let inline get2 (t:^a) = (^a : (member get_Item2 : unit -> string) (t, ())) let inline get2a (t:^a) = (^a : (member Item2 : string) t) 

However, both versions do not work. The first, get2 , will not compile, with "Expected 1 expressions received 2". The second, get2a , will be compiled, but subsequently cannot be used in tuples: "Type (int * string)" does not support operators named "get_Item2".

Is there a way to do this so that there are not many overloads? with noisy annotations OverloadID (annotations not required in F # 2.0)

+4
source share
2 answers

The reason the ItemX static restrictions for F # tuples do not work is because System.Tuple<_,...,_> is just the encoded form of the tuples and not the static representation used by the compiler. See 6.3.2 Expression corrections in the specification.

However, with a little work, you can get the runtime encoding of a given tuple as follows:

 open System //like get2a but generic return type let inline get2b (t:^a) = (^a : (member Item2 : 'b) t) let x = (1,2) let y = (1,2,3) get2b (box x :?> Tuple<int,int>) get2b (box y :?> Tuple<int,int,int>) 
+8
source

You can do this using reflection:

 let inline get (t:^a) = t.GetType().GetProperty("Item2").GetValue(t,null) :?> string 

In addition, I would suggest that tuples are not really an excellent data structure for data transfer, they can be useful inside a function for small operations, but in case of frequent changes in the structure, a tuple can be very painful for working with

+3
source

All Articles