F# 类型成员可以互相引用吗?
我想知道是否有一种方法可以让类型成员相互引用。我想编写如下程序:
type IDieRoller =
abstract RollDn : int -> int
abstract RollD6 : int
abstract RollD66 : int
type DieRoller() =
let randomizer = new Random()
interface IDieRoller with
member this.RollDn max = randomizer.Next(max)
member this.RollD6 = randomizer.Next(6)
member this.RollD66 = (RollD6 * 10) + RollD6
但是,this.RollD66 无法看到 this.RollD6。我可以理解为什么,但似乎大多数函数式语言都有一种方法让函数知道它们提前存在,以便这种或类似的语法是可能的。
相反,我必须执行以下操作,这并没有更多的代码,但似乎前者看起来比后者更优雅,特别是如果有更多这样的情况。
type DieRoller() =
let randomizer = new Random()
let rollD6 = randomizer.Next(6)
interface IDieRoller with
member this.RollDn max = randomizer.Next(max)
member this.RollD6 = rollD6
member this.RollD66 = (rollD6 * 10) + rollD6
有什么建议吗?谢谢!
I was wondering if there is a way to let type members reference each other. I would like to write the following program like this:
type IDieRoller =
abstract RollDn : int -> int
abstract RollD6 : int
abstract RollD66 : int
type DieRoller() =
let randomizer = new Random()
interface IDieRoller with
member this.RollDn max = randomizer.Next(max)
member this.RollD6 = randomizer.Next(6)
member this.RollD66 = (RollD6 * 10) + RollD6
But, this.RollD66 is unable to see this.RollD6. I can sort of see why, but it seems most functional languages have a way of letting functions know that they exist ahead of time so that this or similar syntax is possible.
Instead I've had to do the following, which isn't much more code, but it seems that the former would look more elegant than the latter, especially if there are more cases like that.
type DieRoller() =
let randomizer = new Random()
let rollD6 = randomizer.Next(6)
interface IDieRoller with
member this.RollDn max = randomizer.Next(max)
member this.RollD6 = rollD6
member this.RollD66 = (rollD6 * 10) + rollD6
Any tips? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果类只不过是一个接口实现,则可以使用对象表达式。如果可能的话,我更喜欢这个,因为它简洁。
F#
C#
If the class is nothing more than an interface implementation, you can use an object expression. I prefer this, when possible, for its conciseness.
F#
C#
尝试以下操作:
但是,您可能会发现以下更易于使用(因为 F# 显式实现接口,而 C# 默认情况下隐式实现接口):
Try the following:
However, you may find the following easier to use (as F# implements interfaces explicitly, unlike C# which implements them implicitly by default):