F#类型约束和重载分辨率

Giu*_*ore 5 f# typeclass

我试图在F#中模拟一个类型类的系统; 我想创建配对打印机,它自动实例化对打印功能的正确系列调用.我最近的尝试粘贴在这里,因为F#无法确定正确的过载并立即放弃,因此失败了:

type PrintableInt(x:int) =
  member this.Print() = printfn "%d" x

let (!) x = PrintableInt(x)

type Printer() =
  static member inline Print< ^a when ^a : (member Print : Unit -> Unit)>(x : ^a) =
    (^a : (member Print : Unit -> Unit) x)
  static member inline Print((x,y) : 'a * 'b) =
    Printer.Print(x)
    Printer.Print(y)

let x = (!1,!2),(!3,!4)

Printer.Print(x)
Run Code Online (Sandbox Code Playgroud)

有没有办法这样做?我在游戏开发的环境中这样做,所以我无法负担反射,重新输入和动态转换的运行时开销:要么我通过内联静态地执行此操作,要么我根本不执行此操作:(

Gus*_*Gus 8

你想做的事情是可能的.您可以在F#中模拟类型类,因为Tomas说可能不像Haskell那样惯用.我认为在你的例子中你将类型类型与鸭子类型混合在一起,如果你想使用类型类方法,不要使用成员,而是使用函数和静态成员.

所以你的代码可能是这样的:

type Print = Print with    
  static member ($) (_Printable:Print, x:string) = printfn "%s" x
  static member ($) (_Printable:Print, x:int   ) = printfn "%d" x
  // more overloads for existing types

let inline print p = Print $ p

type Print with
  static member inline ($) (_Printable:Print, (a,b) ) = print a; print b

print 5
print ((10,"hi"))
print (("hello",20), (2,"world"))

// A wrapper for Int (from your sample code)
type PrintableInt = PrintableInt of int with
  static member ($) (_Printable:Print, (PrintableInt (x:int))) = printfn "%d" x

let (!) x = PrintableInt(x)

let x = (!1,!2),(!3,!4)

print x

// Create a type
type Person = {fstName : string ; lstName : string } with
  // Make it member of _Printable
  static member ($) (_Printable:Print, p:Person) = printfn "%s, %s" p.lstName p.fstName

print {fstName = "John"; lstName = "Doe" }
print (1 ,{fstName = "John"; lstName = "Doe" })
Run Code Online (Sandbox Code Playgroud)

注意:我使用运算符来避免手动编写约束,但在这种情况下也可以使用命名的静态成员.更多关于这种技术的信息.