F# instance syntax

岁酱吖の 提交于 2019-12-23 08:56:30

问题


What indicator do you use for member declaration in F#? I prefer

member a.MethodName

this is to many letters and x is used otherwise.


回答1:


I do almost always use x as the name of this instance. There is no logic behind that, aside from the fact that it is shorter than other options.

The options that I've seen are:

member x.Foo     // Simply use (short) 'x' everywhere
member ls.Foo    // Based on type name as Benjol explains
member this.Foo  // Probably comfortable for C# developers
member self.Foo  // I'm not quite sure where this comes from!
member __.Foo    // Double underscore to resemble 'ignore pattern' 
                 // (patterns are not allowed here, but '__' is identifier)

The option based on the type name makes some sense (and is good when you're nesting object expressions inside a type), but I think it could be quite difficult to find reasonable two/three abbreviation for every type name.




回答2:


Don't have a system. Wonder if I should have one, and I am sure there will be a paradigm with its own book some day soon. I tend to use first letter(s) of the type name, like Benjol.

This is a degree of freedom in F# we could clearly do without. :)




回答3:


I tend to use some kind of initials which represent the type so:

type LaserSimulator = 
    member ls.Fire() = 



回答4:


I largely tend to use self.MethodName, for the single reason that self represents the current instance by convention in the other language I use most: Python. Come to think of it, I used Delphi for some time and they have self as well instead of this.

I have been trying to convert to a x.MethodName style, similar to the two books I am learning from: Real World Functional Programming and Expert F#. So far I am not succeeding, mainly because referring to x rather than self (or this) in the body of the method still confuses me.

I guess what I am saying is that there should be a meaningful convention. Using this or self has already been standardised by other languages. And I personally don't find the three letter economy to be that useful.




回答5:


Since I work in the .NET world, I tend to use "this" on the assumption that most of the .NET people who encounter F# will understand its meaning. Of course, the other edge of that sword is that they might get the idea that "this" is the required form.

.NET self-documentation concerns aside, I think I would prefer either: "x" in general, or -- like Benjol -- some abbreviation of the class name (e.g. "st" for SuffixTrie, etc.).




回答6:


The logic I use is this: if I'm not using the instance reference inside the member definition, I use a double underscore ('__'), a la let-binding expressions. If I am referencing the instance inside the definition (which I don't do often), I tend to use 'x'.



来源:https://stackoverflow.com/questions/3912821/f-instance-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!