I've run into a strange syntax in Boo Language Guide :
setter = { value | a = value }
What does the | operator mean?
The documentation of Boo seems to be lacking in this area -- it seems that
setter = { value | a = value }
is shorthand for
setter = def(value):
a = value
Well, having never used Boo, my (educated) guess is that it's for passing parameter to the closure lambda-style functions. In this case, { p | C } refers to an anonymous function taking a single parameter bound to p within the code C.
Adam is correct. The point of the example is to show that lambdas in boo have read and write access to enclosing scope.
That syntax for specifying code blocks (anonymous functions) has been borrowed from Ruby and Smalltalk
Related
Ruby setters—whether created by (c)attr_accessor or manually—seem to be the only methods that need self. qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:
All methods need self/this (like Perl, and I think Javascript)
No methods require self/this is (C#, Java)
Only setters need self/this (Ruby?)
The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: foo.x = y, y = foo.x . C# calls them properties.
Here's a simple example; the same program in Ruby then C#:
class A
def qwerty; #q; end # manual getter
def qwerty=(value); #q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
take away the self.qwerty =() and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:
using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method cannot be invoked without self?
There are certainly lots of cases where self becomes necessary. This is not unique to Ruby, just to be clear:
using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
Same ambiguity is resolved in same way. But while subtle I'm asking about the case where
A method has been defined, and
No local variable has been defined, and
we encounter
qwerty = 4
which is ambiguous—is this a method invocation or an new local variable assignment?
#Mike Stone
Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree:
on a matter of semantics, and
on a central point of fact
First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.
When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation:
ambiguous: lexical ambiguity (lex must 'look ahead')
Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)
AMBIGUOUS: ambiguity knowing everything at the moment of execution
(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,
"qwerty = 4" is UNAMBIGUOUS in C#
when there is no variable defined...
I couldn't agree more. But by the same token, I'm saying
"qwerty = 4" is un-Ambiguous in ruby
(as it now exists)
"qwerty = 4" is Ambiguous in C#
And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,
For "qwerty = 4," ruby UNAMBIGUOUSLY
invokes an existing setter if there
is no local variable defined
You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, except "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.
Let me explain.
Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:
var = expr // assignment
method = expr // setter method invocation
But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:
var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
that is why it's un-Ambiguous, while and C# does this:
symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
For C#, 'later' is still at compile time.
I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.
My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...
But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness?
Well, I think the reason this is the case is because qwerty = 4 is ambiguous—are you defining a new variable called qwerty or calling the setter? Ruby resolves this ambiguity by saying it will create a new variable, thus the self. is required.
Here is another case where you need self.:
class A
def test
4
end
def use_variable
test = 5
test
end
def use_method
test = 5
self.test
end
end
a = A.new
a.use_variable # returns 5
a.use_method # returns 4
As you can see, the access to test is ambiguous, so the self. is required.
Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter. If you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with this., just like the Ruby case.
The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment.
Because otherwise it would be impossible to set local variables at all inside of methods. variable = some_value is ambiguous. For example:
class ExampleClass
attr_reader :last_set
def method_missing(name, *args)
if name.to_s =~ /=$/
#last_set = args.first
else
super
end
end
def some_method
some_variable = 5 # Set a local variable? Or call method_missing?
puts some_variable
end
end
If self wasn't required for setters, some_method would raise NameError: undefined local variable or method 'some_variable'. As-is though, the method works as intended:
example = ExampleClass.new
example.blah = 'Some text'
example.last_set #=> "Some text"
example.some_method # prints "5"
example.last_set #=> "Some text"
Just curious why F# has:
member val Foo = ... with get, set
While omitting the self identifier (e.g. this.).
This is still an instance property. Maybe I am the only one confused when using it. But just bothered me enough to query whoever knows how the language was defined.
With this syntax, the property is almost totally auto-implemented -- all you provide is the initialization code, which essentially runs as part of the constructor.
One of the best-practice guard rails F# puts in place is that it does not let you access instance members before the instance is fully initialized. (wow, crazy idea, right?).
So you would have no use for a self-identifier in auto-props, anyways, since the only code you get to write is init code that can't touch instance members.
Per the MSDN docs (emphasis mine):
Automatically implemented properties are part of the initialization of
a type, so they must be included before any other member definitions,
just like let bindings and do bindings in a type definition. Note that
the expression that initializes an automatically implemented property
is only evaluated upon initialization, and not every time the property
is accessed. This behavior is in contrast to the behavior of an
explicitly implemented property. What this effectively means is that
the code to initialize these properties is added to the constructor of
a class.
Btw, if you try to be a smartass and use the class-level self-identifier to get around this, you'll still blow up at runtime:
type A() as this =
member val X =
this.Y + 10
with get, set
member this.Y = 42
let a = A()
System.InvalidOperationException: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
at Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicFunctions.FailInit()
at FSI_0013.A.get_Y()
at FSI_0013.A..ctor()
at <StartupCode$FSI_0014>.$FSI_0014.main#()
Edit: Worth noting that in upcoming C# 6, they also now allow auto-props with initializers (more F# features stolen for C#, shocker :-P), and there is a similar restriction that you can't use the self-identifier:
class A
{
// error CS0027: Keyword 'this' is not available in the current context
public int X { get; set; } = this.Y + 10;
public int Y = 42;
public A() { }
}
This question already has answers here:
Difference between . and : in Lua
(3 answers)
Closed 7 years ago.
I'm new to Lua and I have work on project, I have an issue unterstanding what ":" I didn't found it on the manual for example how should interpret this piece of code :
res:template{
main = 'functionform.html',
functionjs = '_functionform.js',
functionform = '_functionform.html'
}
The colon operatorPIL in Lua is a little syntatic sugar. It's used in object oriented Lua, to make a regular function call look more like a method call. What it does is pass the object as the self parameter when you call a function. Take this example:
a.myFunction(a, 'foo')
It's equivalent to:
a:myFunction('foo')
In your example, the method call is omiting the parentheses because its only argument is a tablePIL, so your function call without the colon operator would be somthing like:
res.template(res, {
main = 'functionform.html',
functionjs = '_functionform.js',
functionform = '_functionform.html'
})
So as you can see, this little syntatic sugar is pretty handy
From the manual in section 2.5.8:
A function call in Lua has the following syntax:
functioncall ::= prefixexp args
In a function call, first prefixexp and args are evaluated. If the
value of prefixexp has type function, then this function is called
with the given arguments. Otherwise, the prefixexp "call" metamethod
is called, having as first parameter the value of prefixexp, followed
by the original call arguments (see §2.8).
The form
functioncall ::= prefixexp `:´ Name args
can be used to call "methods". A call v:name(args) is syntactic sugar
for v.name(v,args), except that v is evaluated only once.
So res:template{} is the same as res.template(res, {}).
The colon operator adds an additional 'hidden' parameter in method definition and argument in method call. (e.g. this / self)
http://www.lua.org/pil/16.html
So a call to your template function provides the hidden argument 'self' through which you can access the object on which the function is defined.
I'm working with F# 3.1 and I've twice today come across a compile error I can't explain and have had no luck looking up.
In the following code:
type OtherClass(value:int, ?flag:bool) =
member this.DoSomething = (value,flag)
and
MyClass(value:int, ?flag:bool) =
let _dummy = new OtherClass(value,flag)
The compiler says that in my MyClass where I make the call to OtherClass's ctor, the type of flag is incorrect. Specifically, it says that it wants a bool, not a bool option. Yet, it is defined as a bool option according to all that I can see.
Any idea why flag is being seen as a regular bool, and not a bool option as its defined?
Edit:
Upon further reflection, I guess I know whats going on. Optional parameters are inside the method treated as option, but outside, they want the real thing. Something swaps the value out on the call to an option type. So that means that to do what i was trying to do we need something like this
type OtherClass(value:int, ?flag:bool) =
member this.DoSomething = (value,flag)
and
MyClass(value:int, ?flag:bool) =
let _dummy =
match flag with
| None -> new OtherClass(value)
| Some(p) -> new OtherClass(value, p)
This works, but seems a bit verbose. Is there a way to pass an optional directly into an optional parameter like this without resorting to different calls?
Here's the way to do this:
type
OtherClass(value:int, ?flag:bool) =
member this.DoSomething = (value,flag)
and
MyClass(value:int, ?flag:bool) =
let _dummy = new OtherClass(value, ?flag=flag)
Quoting §8.13.6 of the spec:
Callers may specify values for optional arguments in the following
ways:
By propagating an existing optional value by name, such as
?arg2=None or ?arg2=Some(3) or ?arg2=arg2. This can be useful when
building a method that passes optional arguments on to another method.
I am trying to use System.Data.Sqlite with F#. In C#, I have code like
using (DbTransaction dbTrans = con.BeginTransaction()) {
using (SQLiteCommand cmd = con.CreateCommand()) {
//blahblah
}
dbTrans.Commit();
}
But in F#, when I use the similiar two using above I got error of the type bool is not compatible with the type IDisposable...
EDIT I am really sorry for my question. use would work in F# case. I just dont know how to close/delete my quesetions.
To add some details - if you need to explicitly mark the scope where command is valid (to get exactly the same behavior as in your C# example, where cmd id disposed of before calling Commit) you can write:
use dbTrans = con.BeginTransaction()
( use cmd = con.CreateCommand()
cmd.BlahBlahBlah() )
dbTrans.Commit()
The scope is just a part of expression where the symbol is defined, so you can make it explicit using parentheses.
using is just an F# function that you could use before special syntax using use was added. Just FYI, the syntax looks like this:
using (con.BeginTransaction()) (fun dbTrans ->
using (con.CreateCommand()) (fun cmd ->
cmd.BlahBlahBlah() )
dbTrans.Commit() )
Writing the code using use is definitely a better idea (but you can define your functions like using to encapsulate more interesting behavior - e.g. transaction).
in f# it's
use dbTrans = new con.BeginTransaction ()
and
use cmd = con.CreateCommand()
these will dispose when your function ends