F# 类型约束和重载解析

标签 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)

有什么办法吗?我是在游戏开发的上下文中这样做的,所以我无法承受反射、重新键入和动态转换的运行时开销:要么我通过内联静态地执行此操作,要么根本不执行此操作:(

最佳答案

您正在尝试做的事情是可能的。
您可以在 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/

相关文章:

f# - 有没有办法将 llvm 位代码加载到 Mono (F#)

c# - 是否有可能完全用托管 .NET 语言编写 JIT 编译器(针对 native 代码)

linq - 如何将 Expr <'a -> ' b> 转换为 Expression<Func<'a, obj>>

haskell - 为什么类型类难以实现?

reflection - 如何使用 F# 反射库?

generics - F# 编译错误 : Unexpected type application

haskell - 重新定义列表 monad 实例

scala - 确保隐式定义始终具有更高/更低优先级的一般方法

haskell - 函数式编程中的代数结构是什么?

haskell - Haskell 中的孤立实例