Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 17th, 2012  |  syntax: None  |  size: 1.30 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. F# type constraints and overloading resolution
  2. type PrintableInt(x:int) =
  3.   member this.Print() = printfn "%d" x
  4.  
  5. let (!) x = PrintableInt(x)
  6.  
  7. type Printer() =
  8.   static member inline Print< ^a when ^a : (member Print : Unit -> Unit)>(x : ^a) =
  9.     (^a : (member Print : Unit -> Unit) x)
  10.   static member inline Print((x,y) : 'a * 'b) =
  11.     Printer.Print(x)
  12.     Printer.Print(y)
  13.  
  14. let x = (!1,!2),(!3,!4)
  15.  
  16. Printer.Print(x)
  17.        
  18. type Print = Print with    
  19.   static member ($) (_Printable:Print, x:string) = printfn "%s" x
  20.   static member ($) (_Printable:Print, x:int   ) = printfn "%d" x
  21.   // more overloads for existing types
  22.  
  23. let inline print p = Print $ p
  24.  
  25. type Print with
  26.   static member inline ($) (_Printable:Print, (a,b) ) = print a; print b
  27.  
  28. print 5
  29. print ((10,"hi"))
  30. print (("hello",20), (2,"world"))
  31.  
  32. // A wrapper for Int (from your sample code)
  33. type PrintableInt = PrintableInt of int with
  34.   static member ($) (_Printable:Print, (PrintableInt (x:int))) = printfn "%d" x
  35.  
  36. let (!) x = PrintableInt(x)
  37.  
  38. let x = (!1,!2),(!3,!4)
  39.  
  40. print x
  41.  
  42. // Create a type
  43. type Person = {fstName : string ; lstName : string } with
  44.   // Make it member of _Printable
  45.   static member ($) (_Printable:Print, p:Person) = printfn "%s, %s" p.lstName p.fstName
  46.  
  47. print {fstName = "John"; lstName = "Doe" }
  48. print (1 ,{fstName = "John"; lstName = "Doe" })