Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do tuple augmentation

The following code is from chapter 5 of "F# 4.0 Design Patterns".

let a = 1,"car" 
type System.Tuple<'T1,'T2> with 
  member t.AsString() = 
    sprintf "[[%A]:[%A]]" t.Item1 t.Item2 
(a |> box :?> System.Tuple<int,string>).AsString()

The desired output is [[1]:["car"]]

However, a red squiggly appears under AsString(). "The field, constructor or member ‘AsString’ is not defined. Maybe you want one of the following: ToString"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is a bit odd code sample – I suspect the point that this is making is that F# tuples are actually .NET tuples represented using System.Tuple – by showing that an extension to System.Tuple can be invoked on ordinary F# tuples.

I suspect the behaviour of F# has changed and it no longer allows this – it may have been that adding extensions was allowed on System.Tuple, but not on ordinary F# tuples, but the two have became more unified in the compiler.

However, you can do a very similar thing using the .NET-style extension methods:

let a = 1,"car" 

[<System.Runtime.CompilerServices.ExtensionAttribute>]
type TupleExtensions =
  [<System.Runtime.CompilerServices.ExtensionAttribute>]
  static member AsString(t:System.Tuple<'T1,'T2>) = 
    sprintf "[[%A]:[%A]]" t.Item1 t.Item2 

let st = (a |> box :?> System.Tuple<int,string>)
st.AsString()

This can actually be also invoked directly on an F# tuple value:

("car", 32).AsString()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading