Why this closure call doesn't end up in a recursive call? - recursion

I'm new to Groovy and I'm studying closures in the oficial docs. The 'delegate of a closure' topic gives the example bellow:
So, in the number 5, I know that delegate is set default to owner, that in the case is the enclosing closure enclosed.
So, why calling
{ -> delegate }.call()
inside the enclosed closure doesn't end up in a recursive call? Looks like a recursion to me, but if you run the code, isn't a recursion. What I'm missing here?

def enclosed = {
// delegate == owner == enclosed (variable)
{ ->
// When this closure is called return the delegate (enclosed)
delegate
}.call() // Called immediately
// above closure is same as writing
// return delegate
}
// When enclosed in called the delegate is returned immediately
// from the invocation of the inner closure, hence the result of the
// closure call is the closure (delegate) itself
assert enclosed() == enclosed
Keep in mind that whatever is suppose to happen inside enclosed closure will not happen until enclosed() is called. :) Does it depict a clear picture now?

Calling { -> delegate }.call() in the enclosed closure doesn't cause a recursive call because call() is invoked on a different closure; the one created in enclosed. To get a recursive call you can do this: { -> delegate }.call().call(). The first call() returns enclosed, and the second invokes it.

Related

Is console.log asynchronous?

I had an incident in my Angular 6 application the other day involving some code that looked like this:
console.log('before:', value);
this.changeValue(value);
console.log('after:', value);
changeValue() modifies value in some way. I expected to see the unmodified value in the console before the call to changeValue() then the modified value after. Instead I saw the modified value before and after.
I guess it proved that my changeValue() function worked, but it also indicated to me that console.log() is asynchronous--that is, it doesn't print out the value to the console right away; it waits for a bit... and when it finally does print the value, it's the value as it is at that moment. In other words, the first call to console.log() above waited until after the call to changeValue() before printing, and when it did, the value had already changed.
So am I correct in inferring that console.log() is asynchronous. If so, why is that? It causes a lot of confusion when debugging.
No, console.log() is synchronous. It's actually your changeValue() function that doesn't work the way you think.
First, JavaScript doesn't pass variables by reference, but by pointer to object (as do many other languages). So although the variable value inside your function and the variable value in the outer scope both hold the same object, they are still separate variables. Mutatin the object affects both variables, but direct assignments to one variable do not affect the other. For example, this obviously wouldn't work:
function changeValue(x) { x = 123; }
Second, in JavaScript the shorthand assignment a += b does not mutate the existing object stored in a. Instead it works exactly like a = a + b and assigns a new object to the variable. As mentioned above, this only affects the variable inside the function, but doesn't affect the one outside, so your changes are lost after the function returns.
More examples:
function willwork(obj) { obj.foo = "bar"; }
function willwork(obj) { obj["foo"] = 1234; }
function willwork(obj) { obj.push("foo"); }
function wontwork(obj) { obj = "foo"; }
function wontwork(obj) { obj += 123; }
function wontwork(obj) { obj = obj + 123; }

Unexpected Behavior passing weak reference in lambda

If I use this code, the function returns me null as the Resolve worked sometimes and failed sometimes (based on when this was called)
Platform::WeakReference wr(this);
Windows::Foundation::Collections::IAsyncOperation<Object1^>^ asyncTask =
concurrency::create_async(
[wr, timeoutMS](concurrency::cancellation_token token) -> Object1^
{
if (auto refToThis = wr.Resolve<CurrentClass>())
{
// Do something
}
else return null; // The code took this path if the call was made
// immediately, if the call was made from inner
// page or
// even after 5 sec in Main Page init – It always
// worked
}
Where as if I pass this reference in lambda expression it always resolves
Platform::WeakReference wr(this);
Windows::Foundation::Collections::IAsyncOperation<Object1^>^ asyncTask =
concurrency::create_async(
[this, wr, timeoutMS](concurrency::cancellation_token token) -> Object1^
{
if (auto refToThis = wr.Resolve<CurrentClass>())
{
// Do something - It resolves always now
}
else return null;
}
Any clue why this happens? I am new to C++/Cx, I read that its not good to pass this ref in lambda expressions, but the resolve fails if I dont pass
Why the second example always work:
You are capturing this in the lambda closure [], means you are doing a copy of this inside the lambda scope. Since this is probably a ref class it means you increment the reference counter of the pointer on it, meaning this will not be destroyed. When resolving the weak reference, since this is still alive, you are able to retrieve it from the weak reference.
In the first example, you are passing only the weak reference to the lambda closure, since you are probably working with some UI element, if this is destroyed, the weak reference resolution will return nullptr.
You should either pass a weak reference or directly this in the lambda closure, but in the case where you pass this, you should ensure that you will be called by this lambda in order to avoid keeping a reference on an object causing it to never be deleted, creating a memory leak.

Writing a Kotlin util function which provides self-reference in initializer

I'm trying to generalize my hack from an answer to another question.
It should provide a way to reference a value which is not constructed yet inside its initializer (of course, not directly, but in lambdas and object expressions).
What I have at the moment:
class SelfReference<T>(val initializer: SelfReference<T>.() -> T) {
val self: T by lazy {
inner ?: throw IllegalStateException("Do not use `self` until initialized.")
}
private val inner = initializer()
}
fun <T> selfReference(initializer: SelfReference<T>.() -> T): T {
return SelfReference(initializer).self
}
It works, see this example:
class Holder(var x: Int = 0,
val action: () -> Unit)
val h: Holder = selfReference { Holder(0) { self.x++ } }
h.action()
h.action()
println(h.x) //2
But at this point the way in which initializer references the constructed value is self property.
And my question is: is there a way to rewrite SelfReference so that initializer is passed an argument (or a receiver) instead of using self property? This question can be reformulated to: is there a way to pass a lazily evaluated receiver/argument to a function or achieve this semantics some way?
What are the other ways to improve the code?
UPD: One possible way is to pass a function that returns self, thus it would be used as it() inside the initializer. Still looking for other ones.
The best I have managed to produce while still being completely generic is this:
class SelfReference<T>(val initializer: SelfReference<T>.() -> T) {
val self: T by lazy {
inner ?: throw IllegalStateException("Do not use `self` until initialized.")
}
private val inner = initializer()
operator fun invoke(): T = self
}
Adding the invoke operator lets you use it in the following way:
val h: Holder = selfReference { Holder(0) { this().x++ } }
This is the closest I got to make it look like something you would "normally" write.
Sadly I think it is not possible to get completely rid of a explicit access to the element. Since to do that you would need a lambda parameter of type T.() -> T but then you wouldn't be able to call that parameter without an instance of Tand being T a generic there is no clean and safe way to acquire this instance.
But maybe I'm wrong and this helps you think of a solution to the problem
is there a way to rewrite SelfReference so that initializer is passed an argument (or a receiver) instead of using self property? This question can be reformulated to: is there a way to pass a lazily evaluated receiver/argument to a function or achieve this semantics some way?
I'm not sure I completely understand your use case but this may be what you're looking for:
fun initHolder(x: Int = 0, holderAction: Holder.() -> Unit) : Holder {
var h: Holder? = null
h = Holder(x) { h!!.holderAction() }
return h
}
val h: Holder = initHolder(0) { x++ }
h.action()
h.action()
println(h.x) // 2
This works because holderAction is a lambda with a receiver (Holder.() -> Unit) giving the lambda access to the receiver's members.
This is a general solution since you may not be able to change the signature of the respective Holder constructor. It may be worth noting this solution does not require the class to be open, otherwise a similar approach could be done with a subclass using a secondary constructor.
I prefer this solution to creating a SelfReference class when there are only a few number of classes that need the change.
You may want to check for null instead of using !! in order to throw a helpful error. If Holder calls action in it's constructor or init block, you'll get a null pointer exception.
I'm pretty sure you can achieve the same results in a more readable and clear way using something like this:
fun <T> selfReferenced(initializer: () -> T) = initializer.invoke()
operator fun<T> T.getValue(any: Any?, property: KProperty<*>) = this
and later use
val valueName: ValueType by selfReferenced{
//here you can create and use the valueName object
}
Using as example your quoted question https://stackoverflow.com/a/35050722/2196460 you can do this:
val textToSpeech:TextToSpeech by selfReferenced {
TextToSpeech(
App.instance,
TextToSpeech.OnInitListener { status ->
if (status == TextToSpeech.SUCCESS) {
textToSpeech.setLanguage(Locale.UK)
}
})
}
Inside the selfReferenced block you can use the outer object with no restrictions. The only thing you should take care of, is declaring the type explicitly to avoid recursive type checking issues.

Conundrum with init() and dispatch_sync

In a class, I have the following init() function:
init() {
let q = 0
dispatch_sync(queue) {
self._state = State(q)
}
}
where _state is an instance of a struct State and queue a global dispatch queue.
I'm using the dispatch_sync call in order to synchronize the potentially concurrently accessed instance of the class.
I'm running in some weird issue, that the compiler is complaining about using the _state variable before it´s being initialized (namely using it in the block, before it is being initialized):
main.swift:363:37: error: variable 'self._state' used before being initialized
dispatch_sync(s_sync_queue) {
^
However, the sole purpose of using the dispatch queue and the block is to initialize the ivar.
The compiler even states, the code would return without initializing the variable _state:
main.swift:372:5: error: property 'self._state' not initialized
}
^
albeit, clearly, due to dispatch_sync the function init cannot return without leaving the variable _state uninitialized.
So, how could I solve the issue in an efficient manner?
One option is to declare _state as optional if you can.(If there is no harm to do that)
var _state:State?
if you make this optional you can use it in dispatch_sync.

How to reference an anonymous JavaScript function?

I'm trying to call a Page Method using a jQuery 'attached' event function, in which I like to use the closure to keep the event target local, as below, but page method calls declare several 'error' functions, and I would like to use one function for all of them. If, in the below code, I was handling an error and not success, how could I use my single, anonymous handler for all 3 error functions?
$(":button").click(function () {
var button = this;
PageMethods.DoIt(
function (a, b, c) {
alert(button);
});
});
This example passes an anonymous function for the success callback. There is only one of these. If I was passing an error callback, how could I use 'function (e, c, t)' for all 3 error callbacks?
ADDED: What I would like to do here is trigger an AJAX call whenever the user clicks a toggle button (checkbox), but to improve responsiveness, I want to toggle the button state immediately, and only 'untoggle' it if the AJAX call fails.
Now, in my client-side click() event handler, I would like to use anonymous functions inside the scope of click()' so that the functions have access to thethisevent argument, but I don't want to 'declare' three functions for theonTimeout,onError, and 'onAbort arguments of the PageMethods.MyFunction function. if I declare a named function outside of the click handler, it no longer has access to the 'this' parameter of the click() event handler.
If your goal is to keep this function out of global scope, use the module pattern:
(function() {
function asplode() {
alert('Your head asplode.');
}
$('body').click(asplode);
})();
I think you can put a variable with name in front of it, like this:
var myFunction = function(a, b, c) { ...
It's been a while I haven't done this but you could give it a try.
You have to assign an anonymous function to a variable using var (always use var, otherwise a variable gets global scope, which may cause unexpected results (e.g., never declare variable i globally)). That's the only way to reference it:
var myFunction = function (a, b, c) {
/* tum de dum */
}; // don't forget this semicolon
Then you can use this function in different places:
$(":button").click(myFunction);
/* don't put braces after the function name when referencing it,
else it will be called immediately */
You can find more information about function expressions and function declarations in the article Named function expressions demystified.
You can't. The whole point of an anonymous function is that it has no name and thus cannot be referenced. (In fact, "anonymous" is basically the Greek word for "unnamed".)
If you want to reference it, you need to give it a name.
From inside the anonymous function, you can reference it as arguments.callee (this is how anonymous recursion is achieved).
If I understand correctly what you want to do, you may be able to accomplish it like this:
function handler(a, b, c) {
alert(this); // button
}
$(":button").click(function () {
var button = this;
PageMethods.DoIt(function () {
handler.call(button, a, b, c);
});
});

Resources