我正在尝试在 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)
有什么办法吗?我是在游戏开发的上下文中这样做的,所以我无法承受反射、重新键入和动态转换的运行时开销:要么我通过内联静态地执行此操作,要么根本不执行此操作:(
最佳答案
您正在尝试做的事情是可能的。
您可以在 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" })
注意:我使用了一个运算符来避免手动编写约束,但在这种情况下也可以使用命名的静态成员。
有关此技术的更多信息 here .
关于F# 类型约束和重载解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9868327/