F#类型约束和重载解决方案 [英] F# type constraints and overloading resolution

查看:76
本文介绍了F#类型约束和重载解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在F#中模拟类型类的系统;我想创建一个配对打印机,该打印机自动实例化对打印功能的正确调用序列.我的最新尝试(粘贴在此处)失败了,因为F#无法识别正确的重载并立即放弃:

I am trying to emulate a system of type classes in F#; I would like to create pair printer which automatically instantiates the right series of calls to the printing functions. My latest try, which is pasted here, fails miserably since F# cannot identify the right overload and gives up immediately:

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)

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

Is there any way to do so? I am doing this in the context of game development, so I cannot afford the runtime overhead of reflection, retyping and dynamic casting: either I do this statically through inlining or I don't do it at all :(

推荐答案

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

What you're trying to do is possible. You can emulate typeclasses in F#, as Tomas said maybe is not as idiomatic as in Haskell. I think in your example you are mixing typeclasses with duck-typing, if you want to go for the typeclasses approach don't use members, use functions and static members instead.

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

So your code could be something like this:

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" })

注意:我使用运算符来避免手工编写约束,但是在这种情况下,也可以使用命名的静态成员. 此处.

Note: I used an operator to avoid writing the constraints by hand, but in this case is also possible to use a named static member. More about this technique here.

这篇关于F#类型约束和重载解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆