Difference between class-level and member-level self-identifier in F#? - f#

Is there any semantic difference between class-level and member-level self-identifiers in F#? For example, consider this class:
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.Data = data
member this.PrintMessage() =
printfn "Creating MyClass2 with Data %d" this.Data
Versus this class:
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.Data = data
member this.PrintMessage() =
printfn "Creating MyClass2 with Data %d" self.Data
The only difference is that the implementation of PrintMessage references this in one vs. self in the other. Is there any difference in semantics? If not, is there a stylistic reason to prefer one over the other?

There's no real semantic difference between the two. As a rule of thumb, I suggest going with your first example - prefer the identifier that's closer in scope, it makes it easier to read and refactor the code later. As a side note, people will usually use this both for class and member-level identifiers, in which case the member-level one shadows class-level one.
In these kind of scenarios, it's useful to look at the compiled code in a disassembler like ILSpy. If you do that, you'll find that the only difference is an extra null check that is inserted in self.Data case.
On the other hand, there is a difference between a class that uses a class-level identifier and one that doesn't (a series of initialization checks get inserted into all the class members). It's best to avoid having them if possible, and your example can be rewritten to not require one.

As mentioned by scrwtp, this seems to be a commonly used identifier and it is my preference. Another very common one is x. I tend to use the class-level identifier when it's used multiple times throughout a class and of course when it's used in the constructor. And in those cases I would use __ (two underscores) as the member level identifier, to signify that the value is ignored. You can't use _ and actually ignore it as it's a compile error, but linting tools will often consider __ as the same thing and avoid giving you a warning about an unused identifier.
When you add a class-level identifier and don't use it you get a warning:
The recursive object reference 'self' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference.
Consider this code:
type MyClass() =
member self.X = self
type MyClassAsSelf() as self =
member __.X = self
type MyClassAsSelfUnused() as self = // <-- warning here
member __.X = ()
This is what these classes look like after compiling/decompiling:
public class MyClass
{
public Program.MyClass X
{
get
{
return this;
}
}
public MyClass() : this()
{
}
}
public class MyClassAsSelf
{
internal FSharpRef<Program.MyClassAsSelf> self = new FSharpRef<Program.MyClassAsSelf>(null);
internal int init#22;
public Program.MyClassAsSelf X
{
get
{
if (this.init#22 < 1)
{
LanguagePrimitives.IntrinsicFunctions.FailInit();
}
return LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.MyClassAsSelf>(this.self.contents);
}
}
public MyClassAsSelf()
{
FSharpRef<Program.MyClassAsSelf> self = this.self;
this..ctor();
this.self.contents = this;
this.init#22 = 1;
}
}
public class MyClassAsSelfUnused
{
internal int init#25-1;
public Unit X
{
get
{
if (this.init#25-1 < 1)
{
LanguagePrimitives.IntrinsicFunctions.FailInit();
}
}
}
public MyClassAsSelfUnused()
{
FSharpRef<Program.MyClassAsSelfUnused> self = new FSharpRef<Program.MyClassAsSelfUnused>(null);
FSharpRef<Program.MyClassAsSelfUnused> self2 = self2;
this..ctor();
self.contents = this;
this.init#25-1 = 1;
}
}
Note that there is a check that a variable has been set in the constructor. If the check fails then a function is called: LanguagePrimitives.IntrinsicFunctions.FailInit(). This is the exception thrown:
System.InvalidOperationException: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
I guess the warning is there just so that you can avoid the slight overhead of an unnecessary runtime check. However, I don't know how to construct a situation where the error is thrown, so I don't know the exact purpose of the check. Perhaps someone else can shed light on this?

Related

How to use a variable from a different class

I have a rather simple question. How can I use variables from different classes in dart?
class ContainsVariable {
var variable = 1;
}
class DoesNotContainVariable {
var useVariable = variable + 1; // This gives me an error saying:
// Undefined name 'variable'
}
Having their own scope is a very fundamental feature of classes in Object Oriented Programming, corresponding to OOP principles.
Also note that from your code, it seems that you have not properly understood the idea of instantiation in Object Oriented Programming, since you are trying to set an instance variable without instantiating the class. I highly suggest to look into this topic to gain more understanding.
That being said, there are most definitely many ways to achieve what you want. Since your code sample is very general, I'm not exactly sure what you are trying to do, so I'll provide 2 examples, which might be useful:
Option 1 - static member variable
You can make a static (class level) member, which will be the same for all objects.
class ContainsVariable {
static var variable = 1;
}
class DoesNotContainVariable {
var useVariable = ContainsVariable.variable + 1; // here, you are using a
// static (class) variable,
// not an instance variable.
// That is why you are using
// the class name.
}
Option 2 - instantiation
You can instantiate the class - by creating an object of that class - and access the member of that object. Notice that there is no static statement here.
class ContainsVariable {
var variable = 1;
}
class DoesNotContainVariable {
var instanceOfContainsVariable;
var useVariable;
DoesNotContainVariable(){ // this is a constructor function
var instanceOfContainsVariable = new ContainsVariable();
useVariable = instanceOfContainsVariable.variable + 1;
}
}

What is "self" used for in Swift?

I am new to Swift and I'm wondering what self is used for and why.
I have seen it in classes and structures but I really don't find them essential nor necessary to even mention them in my code. What are they used for and why? In what situations it's necessary to use it?
I have been reading lots of questions and answers for this question but none of them fully answers my questions and they always tend to compare it with this as in Java, with which I'm not familiar whatsoever.
Yes it is the same as this in Java and self in Objective-C, but with Swift, self is only required when you call a property or method from a closure or to differentiate property names inside your code, such as initializers. So you can use almost all of your class components safely without using self unless you are making the call from a closure.
“The self Property Every instance of a type has an implicit property
called self, which is exactly equivalent to the instance itself. You
use the self property to refer to the current instance within its
own instance methods.
The increment() method in the example above could have been written
like this:
func increment() {
self.count += 1
}
In practice, you don’t need to write self in your code very often.
If you don’t explicitly write self, Swift assumes that you are
referring to a property or method of the current instance whenever you
use a known property or method name within a method. This assumption
is demonstrated by the use of count (rather than self.count)
inside the three instance methods for Counter.
The main exception to this rule occurs when a parameter name for an
instance method has the same name as a property of that instance. In
this situation, the parameter name takes precedence, and it becomes
necessary to refer to the property in a more qualified way. You use
the self property to distinguish between the parameter name and the
property name.
Here, self disambiguates between a method parameter called x and
an instance property that is also called x:”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2 Prerelease).”
This is how Ray Wenderlich recommends the use of self in Swift for their tutorials:
Use of Self
For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.
Use self when required to differentiate between property names and arguments in initializers, and when referencing properties in closure expressions as required by the compiler:
class BoardLocation {
let row: Int, column: Int
init(row: Int, column: Int) {
self.row = row
self.column = column
let closure = {
println(self.row)
}
}
}
And this is GitHub's recommendations on self for their applications:
Only explicitly refer to self when required
When accessing properties or methods on self, leave the reference to self implicit by default:
private class History {
var events: [Event]
func rewrite() {
events = []
}
}
Only include the explicit keyword when required by the language — for example, in a closure, or when parameter names conflict:
extension History {
init(events: [Event]) {
self.events = events
}
var whenVictorious: () -> () {
return {
self.rewrite()
}
}
}
Rationale: This makes the capturing semantics of self stand out more in closures, and avoids verbosity elsewhere.
You will also use self a lot when creating your extensions, example:
extension Int {
func square() -> Int {
return self * self
}
// note: when adding mutating in front of it we don't need to specify the return type
// and instead of "return " whatever
// we have to use "self = " whatever
mutating func squareMe() {
self = self * self
}
}
let x = 3
let y = x.square()
println(x) // 3
printlx(y) // 9
now let's say you want to change the var result itself
you have to use the mutating func to make change itself
var z = 3
println(z) // 3
now let's mutate it
z.squareMe()
println(z) // 9
// now let's see another example using strings :
extension String {
func x(times:Int) -> String {
var result = ""
if times > 0 {
for index in 1...times{
result += self
}
return result
}
return ""
}
// note: when adding mutating in front of it we don't need to specify the return type
// and instead of "return " whatever
// we have to use "self = " whatever
mutating func replicateMe(times:Int){
if times > 1 {
let myString = self
for index in 1...times-1{
self = self + myString
}
} else {
if times != 1 {
self = ""
}
}
}
}
var myString1 = "Abc"
let myString2 = myString1.x(2)
println(myString1) // "Abc"
println(myString2) // "AbcAbc"
now let's change myString1
myString1.replicateMe(3)
println(myString1) // "AbcAbcAbc"
In what situations it's necessary to use it
It is necessary to use it only when the name of a local variable overshadows the name of a property.
However, as a matter of style (and readability), I always use it:
I use it with property names, because otherwise I am left wondering what this variable is (since it is neither locally declared nor an incoming parameter).
I use it as the receiver of function (method) calls, in order to differentiate such methods from top-level or local functions.
This is why we need self.
When we define a class, like:
class MyClass {
func myMethod()
}
We are creating a "Class Object". Yes, Class is an object too.
Then no matter how many instances are created using the class, all instances will have a reference pointer to its Class Object.
You can imagine that all instance methods defined by the Class are in the Class Object, and there will be only one copy of them.
That means all instances created using the Class are sharing the same method.
Now imagine you are the myMethod in the Class Object, and because you are shared for all instances, you must have a way to tell which instance you are working on.
When someone says instance1.myMethod(), it means "Hi! myMethod, please do your work and instance1 is the object you are working on".
To reference the object that the caller sent to you, use self.
“In practice, you don’t need to write self in your code very often. If
you don’t explicitly write self, Swift assumes that you are referring
to a property or method of the current instance whenever you use a
known property or method name within a method.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itun.es/tw/jEUH0.l
The reserved word self in Swift is similar to this but it's not the same as in Java or JavaScript.
As #Dave Gomez correctly quoted:
Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself.
Here lies one of the main differences, because:
"Every instance" in Swift (at least for now) is almost every-thing.
In Java, for example, you can only use the word this inside an instance scope, in Swift you can use it almost every-where.
Here are a few examples:
//Example 1:
var x="foo"
x.self="bar".self//compiles and run
//Example 2:
print.self(x);//compiles and run
//Example 3:
func myOther(self otherSelf:Person){}
myOther(self: personObject);//compiles and run
//Example 4:
class Foo{
var bar=""
init(){
self.addSome()//this would be the same in Java
}
func addSome(){
//But definitely not this:
self.self.bar.self.self="some".self.self
}
}
//Guess what - also compiles and run...
let f=Foo()
print(f.bar)
See : Why 'self.self' compiles and run in swift for more information.
I arrived at this question while searching for self as a class function, which looks like this: Int.self, String.self, or YourClass.self
Previously, as near as I can tell, only Dmitri Pavlutin's answer touches on this, when he said:
When self is accessed in a type method (static func or class func), it refers to the actual type (rather than an instance).
When self is used this way, it actually returns what in Swift is called a Metatype. You can read the Swift documentation page on Types for more information.
There is also an article with more details about using and understanding metatypes called "What's .self, .Type and .Protocol? Understanding Swift Metatypes" on swiftrocks.com.
"How to use correctly 'self' keyword in Swift" explains self in detail.
self is a property on the instance that refers to itself. It's used to access class, structure and enumeration instance within methods.
When self is accessed in a type method like static func or class func, it refers to the actual type rather than an instance.
Swift allows omitting self when you want to access instances properties.
When a method parameter has the same name as an instance property, you have to explicitly use self.myVariable = myVariable to make a distinction.
Notice that method parameters have a priority over instance properties.
I'm a total noob at coding in general - and whilst these answers are great, from the perspective of a total noob who just wants it answered as practically as possible without all these difficult words and concepts, here's my Super Noob dumbed down version:
'self' is used because the coding application doesn't know which variable to use if you type the variable in the scope of your functions. It's all about the scope and making it clear which variable you're using if some other variable has the same name. Scope is the area inside the curly {} brackets. so for example:
{ scope1 {scope2} }
Here you don't need to use self:
class example {
private var exampleVar = “this is the class scope variable”
func x() {
//You don't have to use self here
print(exampleVar)
}
}
Here you do need to use self:
class example {
private var exampleVar = “this is the class scope variable”
func x(_ exampleVar: String) {
//It would be confusing which exampleVar is used here so you should use self
print(exampleVar)
print(self.exampleVar)
}
}
There's also this situation:
class example {
private var exampleVar = “this is the class scope variable”
func x() {
randomMethod { _ in
//This is not the class scope here, so we need to use self here.
//You will be flagged during build time of this if you don't use self.
print(self.exampleValue)
}
}
}
self is a property on the instance that refers to itself. It's used to access the class, structure and enumeration instance within methods.
When a method parameter has the same name as an instance property, you have to explicitly use self.myVariable = myVariable to make a distinction.
Notice that method parameters have a priority over instance properties.
struct Weather {
let windSpeed: Int
let chanceOfRain: Int
init(windSpeed: Int, chanceOfRain: Int) {
self.windSpeed = windSpeed
self.chanceOfRain = chanceOfRain
}
func isDayForWalk() -> Bool {
let comfortableWindSpeed = 5
let acceptableChanceOfRain = 30
return self.windSpeed <= comfortableWindSpeed
&& self.chanceOfRain <= acceptableChanceOfRain
}
}
// A nice day for a walk
let niceWeather = Weather(windSpeed: 4, chanceOfRain: 25)
print(niceWeather.isDayForWalk()) // => true
I have an elegant case for using self in Swift. I use it in blocks like this:
class MyBase {
private var baseValue: Int = 100
var block: ((Int)->())? = nil
func baseMethod(anotherValue: Int) {
guard let b = block else { return }
b(baseValue + anotherValue)
}
...
}
class MyClass {
init()
{
// Define base class block.
// This may hold self in block causing memory leaks
// if self is a strong reference
block = {
// indicate self is a weak reference
[weak self] (para) in
// guaranty self existence
guard let this = self else {return}
let value = this.value1 + para
// this call passes value to other obj's method
this.obj.method(value)
return
}
}
func callBaseBlock(otherValue: Int) {
baseMethod(otherValue)
}
private var value1: Int = 1 // ini value
private var obj: OtherClass // another class with method defined
...
...
}
This way, I guarantee that there will be no strong references to self in the block. The syntax is very clear. I use this way to prevent memory leaks.

How to inherit the same generic interface twice with different types in F# 3.0 [duplicate]

In C#, I can implement a generic interface twice on one class, using two different type-parameters:
interface IFoo<T> { void Foo(T x); }
class Bar : IFoo<int>, IFoo<float>
{
public void Foo(int x) { }
public void Foo(float y) { }
}
I would like to do the same thing in F#:
type IFoo<'a> = abstract member Foo : 'a -> unit
type Bar() =
interface IFoo<int> with
[<OverloadID("int")>]
member this.Foo x = ()
interface IFoo<float> with
[<OverloadID("float")>]
member this.Foo x = ()
But it gives a compiler error:
This type implements or inherits the same interface at different generic instantiations 'IFoo<float>' and 'IFoo<int>'. This is not permitted in this version of F#.
I can't find any discussion of this issue on the web. Is such use frowned upon for some reason? Are there plans to allow this in an upcoming release of F#?
Right now I don't know of plans to allow this.. The feature has been planned and is, at least partially (see comments) implemented in F# 4.0.
I think the only reasons its currently disallowed are that it's non-trivial to implement (especially with F# type inference), and it rarely arises in practice (I only recall one customer ever asking about this).
Given an infinite amount of time and resources, I think this would be allowed (I can imagine this being added to a future version of the language), but right now it does not seem like this is a feature worth the effort of supporting. (If you know a strong motivating case, please mail fsbugs#microsoft.com.)
EDIT
As an experiment for the curious, I wrote this C#:
public interface IG<T>
{
void F(T x);
}
public class CIG : IG<int>, IG<string>
{
public void F(int x) { Console.WriteLine("int"); }
public void F(string x) { Console.WriteLine("str"); }
}
and referenced it from F# (with comments suggesting the results)
let cig = new CIG()
let idunno = cig :> IG<_> // type IG<int>, guess just picks 'first' interface?
let ii = cig :> IG<int> // works
ii.F(42) // prints "int"
let is = cig :> IG<string> // works
is.F("foo") // prints "str"
so this is what typically happens on this 'boundary' stuff with F# - F# can consume this stuff ok, even if you can't author the same stuff from within the language.
There is a reasonable although not elegant way to do it, create a new type for each interface here is an example of consuming multiple events from an ESB (nSvcBus) which requires that each event corresponds to an implemented interface. The first type below contains the generic 'handler' code, the other types just implement the interface and call to the generic handler
type public nSvcBusEvents() =
member this.HandleEvents(msg:IEvent) = ()
//handle messages ie: let json = JsonConvert.SerializeObject(msg)
type public ActionLoggedHandler() =
interface IHandleMessages<Events.ActionLoggedEvent> with
member this.Handle(msg : ActionLoggedEvent) =
nSvcBusEvents().HandleEvents(msg)
type public ActionCompletedHandler() =
interface IHandleMessages<Events.ActionCompletedHandler> with
member this.Handle(msg : ActionCompletedHandler) =
nSvcBusEvents().HandleEvents(msg)
type public ActionFailedHandler() =
interface IHandleMessages<Events.ActionFailedHandler> with
member this.Handle(msg : ActionFailedHandler) =
nSvcBusEvents().HandleEvents(msg)

Implementing the same interface at different generic instantiations

In C#, I can implement a generic interface twice on one class, using two different type-parameters:
interface IFoo<T> { void Foo(T x); }
class Bar : IFoo<int>, IFoo<float>
{
public void Foo(int x) { }
public void Foo(float y) { }
}
I would like to do the same thing in F#:
type IFoo<'a> = abstract member Foo : 'a -> unit
type Bar() =
interface IFoo<int> with
[<OverloadID("int")>]
member this.Foo x = ()
interface IFoo<float> with
[<OverloadID("float")>]
member this.Foo x = ()
But it gives a compiler error:
This type implements or inherits the same interface at different generic instantiations 'IFoo<float>' and 'IFoo<int>'. This is not permitted in this version of F#.
I can't find any discussion of this issue on the web. Is such use frowned upon for some reason? Are there plans to allow this in an upcoming release of F#?
Right now I don't know of plans to allow this.. The feature has been planned and is, at least partially (see comments) implemented in F# 4.0.
I think the only reasons its currently disallowed are that it's non-trivial to implement (especially with F# type inference), and it rarely arises in practice (I only recall one customer ever asking about this).
Given an infinite amount of time and resources, I think this would be allowed (I can imagine this being added to a future version of the language), but right now it does not seem like this is a feature worth the effort of supporting. (If you know a strong motivating case, please mail fsbugs#microsoft.com.)
EDIT
As an experiment for the curious, I wrote this C#:
public interface IG<T>
{
void F(T x);
}
public class CIG : IG<int>, IG<string>
{
public void F(int x) { Console.WriteLine("int"); }
public void F(string x) { Console.WriteLine("str"); }
}
and referenced it from F# (with comments suggesting the results)
let cig = new CIG()
let idunno = cig :> IG<_> // type IG<int>, guess just picks 'first' interface?
let ii = cig :> IG<int> // works
ii.F(42) // prints "int"
let is = cig :> IG<string> // works
is.F("foo") // prints "str"
so this is what typically happens on this 'boundary' stuff with F# - F# can consume this stuff ok, even if you can't author the same stuff from within the language.
There is a reasonable although not elegant way to do it, create a new type for each interface here is an example of consuming multiple events from an ESB (nSvcBus) which requires that each event corresponds to an implemented interface. The first type below contains the generic 'handler' code, the other types just implement the interface and call to the generic handler
type public nSvcBusEvents() =
member this.HandleEvents(msg:IEvent) = ()
//handle messages ie: let json = JsonConvert.SerializeObject(msg)
type public ActionLoggedHandler() =
interface IHandleMessages<Events.ActionLoggedEvent> with
member this.Handle(msg : ActionLoggedEvent) =
nSvcBusEvents().HandleEvents(msg)
type public ActionCompletedHandler() =
interface IHandleMessages<Events.ActionCompletedHandler> with
member this.Handle(msg : ActionCompletedHandler) =
nSvcBusEvents().HandleEvents(msg)
type public ActionFailedHandler() =
interface IHandleMessages<Events.ActionFailedHandler> with
member this.Handle(msg : ActionFailedHandler) =
nSvcBusEvents().HandleEvents(msg)

Are parsers generated by FSYacc thread safe?

If I generate a parser using FSYacc will it be thread safe?
The only reason I ask is because the functions
Parsing.rhs_start_pos and Parsing.symbol_end_pos
don't appear to have any state passed into them, which would lead me to assume that they are getting the current NonTerminal/Symbols from a shared location, is this correct?
After reflecting the code I see that they are getting the postion from a static property
internal static IParseState parse_information
{
get
{
return parse_information;
}
set
{
parse_information = value;
}
}
Is this correct? If so what can I do about it?
Edit: I also see a static method called set_parse_state
public static void set_parse_state(IParseState x)
{
parse_information = x;
}
But that still wont solve my problem...
I really don't like to answer my own question, however since this could save someone else a world of grief someday I will.
It turns out that the functions provided in the parsing module are NOT thread safe.
What you can do however is access the parseState "variable", which is of type IParseState, in your nonterminal action.
For example (rough but work with me):
If you have a NonTerminal like
%token<string> NAME
%%
Person:
NAME NAME { $1 (* action *) }
The code that gets generated is:
(fun (parseState : Microsoft.FSharp.Text.Parsing.IParseState) ->
let _1 = (let data = parseState.GetInput(1) in
(Microsoft.FSharp.Core.Operators.unbox data : string)
) in
Microsoft.FSharp.Core.Operators.box((_1) : 'Person)
);
So you can interact with that parseState object in the same fashion.
%token<string> NAME
%%
Person:
NAME NAME { parseState.DoStuff(); }
The rhs_start_pos method basically does this:
let startPos,endPos = parseState.InputRange(n)
and the symbol_end_pos does this:
let startSymb,endSymb = parseState.ResultRange
I hope this helps

Resources