30 people like it.

Member constraints on records

Demonstrates explicit member syntax as applied to record fields

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
module Test =
    let inline name (x : ^T) = (^T : (member Name : string) (x))

    type Person =
        {
            Name : string
            Age : int
        }

    let p : Person = { Name = "Tim"; Age = 29 }
    // error FS0001: The type 'Person' does not support any operators named 'get_Name'
    // printfn "%s" (name p)

    type Person2(name : string, age : int) =
        member this.Name = name
        member this.Age = age

    let p2 = Person2("Tim", 29)
    // works
    printfn "%s" (name p2)
val name : x:'T -> string (requires member get_Name)

Full name: Script.Test.name
val x : 'T (requires member get_Name)
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
type Person =
  {Name: string;
   Age: int;}

Full name: Script.Test.Person
Person.Name: string
Person.Age: int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val p : Person

Full name: Script.Test.p
Multiple items
type Person2 =
  new : name:string * age:int -> Person2
  member Age : int
  member Name : string

Full name: Script.Test.Person2

--------------------
new : name:string * age:int -> Person2
val name : string
val age : int
val this : Person2
member Person2.Name : string

Full name: Script.Test.Person2.Name
member Person2.Age : int

Full name: Script.Test.Person2.Age
val p2 : Person2

Full name: Script.Test.p2
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view New version

More information

Link:http://fssnip.net/3z
Posted:6 years ago
Author:Tim Robinson
Tags: generic , record