Suppose, I have the following code (in C-like syntax):
void foo(int arg) { ... }
int bar() {
...
// call with continuation
...
}
foo ( bar() )
// after foo invocation
1) Function foo invokes function bar, which is running until it reaches the line with call with continuation.
2) At this line a continuation function is created. It represents the rest of bar and foo. The continuation function is passed as an argument to call with continuation function.
3) The call with continuation function does whatever it wants with the argument (e.g. it may just store in a global variable) and returns.
4) Once the call with continuation returns we immediately jump to the line with "after foo invocation" and the rest of bar and foo are not executed.
5) In order to continue execution of bar and foo we should explicitly invoke the continuation function (created in (2) and probably stored in (3)). Once the continuation function is invoked the execution continues immediately after the call with continuation.
Is it correct? Am I missing something about undelimited continuations?
No. Typically, undelimited continuations (eg created with Scheme's call/cc) jump when you invoke the continuation, not when you call call/cc (aka call-with-current-continuation).
So, fleshing out your example:
continuation savedk;
void foo(int arg) { ... }
int bar() {
...
call/cc(handler)
// after call/cc
println "after call/cc"
...
}
void handler(continuation k) {
savedk = k
}
foo ( bar() )
// after foo invocation
Execution starts. We enter bar (we haven't entered foo yet; we'll do that when we get done with bar).
When we hit the call to call/cc in bar, the "program context" is turned into an object called a continuation. At this point, the program context consists of "finish executing bar, then call foo on the result, and then do whatever comes after the foo invocation". The continuation is passed to the function given as an argument to call/cc, which is handler in my example above.
handler does something with the continuation. Let's assume it stores it in a global variable. Then it returns to the point right after the call/cc call, still inside of bar.
Let's say we print something out at this point. Then bar finishes and we call foo, and it finishes.
If we now apply the continuation in savedk, control jumps back into bar and restores the program context to "finish executing bar, then call foo on the result, and then do whatever comes after the foo invocation". So we get another line printed. In fact, if we don't clear the savedk variable or test some other state, we might get an infinite loop if "do whatever comes after the foo invocation" is call savedk again!
Related
I have the following code in Kotlin:
fun iterate(first: String, second: String, iter: Int, func: (String, String) -> String) {
for(i in 0..iter)
println(func(first, second))
}
fun concatenation(one: String, two: String): String {
return "$one $two";
}
fun main(args: Array<String>) {
iterate("Me", "You", 5, ::concatenation)
iterate("Another", "One", 6) {a, b -> a + b}
}
Can anyone explain what's happening in curly brackets in the second call of iterate function? Am I overriding it?
Also, I tried to swap func and iter paratemers in function declaration. This way I am not able anymore to use curly brackets in the second call and insert a code, because I don't know where to put iter argument.
Your function iterate() takes four parameters: two Strings, and Int, and a function.
When you call iterate(), you can give the String arguments in several ways: for example, you could give the name of a variable holding the String (such as one); or you could give a literal String value (such as "Me").
And you can give the function argument in both of those ways, too.*
The equivalent of the first way is to give a reference to an existing function. That's what ::concatenation is. (:: is used to create function references.)
The equivalent of the second way is to use a lambda, which is a way of writing out the contents of a function. {a, b -> a + b} is a lambda: it's a function which takes two parameters, and returns their concatenation. (In this case the compiler can tell from the context that the two parameters must be Strings; in other cases, you might need to specify their types.)
What's tricky about the code in this question is that the lambda doesn't look like it's being passed as an argument to the function! It's outside the parens:
iterate("Another", "One", 6) {a, b -> a + b}
And this is a feature that's specific to Kotlin: if the last parameter is a function, you can put the lambda after the close paren. (And, if that's the only argument, you can omit the parens entirely.)
So it means exactly the same as:
iterate("Another", "One", 6, {a, b -> a + b})
This may look confusing, but it supports function calls that look like new language syntax. For example, you may have used the with() function:
with (someObject) {
// In here, ‘this’ refers to someObject.
}
That's not a keyword in the language; it's simply a normal function which takes its action as the last parameter.
So I bet you can now see the answer to your last question. If you were to swap the iter and func params around, you'd have to call it like:
iterate("Another", "One", {a, b -> a + b}, 6)
(Because func is no longer the last parameter, it has to be inside the parens now.)
(* There are additional ways to specify string params and function params, too, but there's no room to go into them all here!)
Your func parameter's type is a function - its type is (String, String) -> String which means it takes two String parameters (in the parentheses) and returns a String (after the arrow).
That's what all function types look like, (x) -> y. A function type that takes no parameters and doesn't return a value has a type () -> Unit (because every function returns something in Kotlin, Unit is the "no meaningful value" type).
So for your func parameter, you can pass in any function with that type - takes two strings, returns a string. Your concatenation function matches that, so you can pass it in - you're using a function reference, ::concatenation which is a way to pass that function - it's a reference to it.
With your second iterate call, you're creating a function object to pass in, instead of referring to one that's declared as an actual method on the class. You're using a lambda that takes two parameters, a and b, and calls + on them (and implicitly returns that value as the result).
Now you're not saying that they're Strings here (you could declare their types explicitly if you wanted), but the type system is basically checking that this can apply to two String variables, and that the result of + on those would also be a String. So it all works fine, and it can be used in your iterate function.
Like #IR42 says in the comments, you're using a trailing lambda - basically when the last parameter in a function call is a lambda, instead of keeping it in the parentheses, you can move it outside (and remove the parentheses if the lambda was the only thing in there).
But this only works when it's the last parameter - otherwise it wouldn't know for sure which one you'd moved out! - which is why you can't change the order and keep the trailing lambda. You can switch up the order, but the call will have to be like this:
iterate("Me", "You", ::concatenation, 5)
iterate("Another", "One", {a, b -> a + b}, 6)
The documentation probably explains it very well but I do not see the difference between this 2 commands in my case :
method dir {} {
puts "method dir..."
}
method pseudomethod {} {
set vardir [my dir]
set vardir [[self] dir]
}
The only difference I can see is that with [self] I can pass it as an argument in a procedure and not with my.
What is the best solution in my case ?
Both solutions have equal performance ?
The self command (with no extra arguments) is equivalent to self object which returns the current public name of the object that is executing the method (you can rename the object). The self command overall provides access to bits of “runtime” state.
The my command is actually the object's internal name; it's created in each object's instance namespace. You can invoke all exported and non-exported methods via my, unlike with the public name. This makes it useful for both calling your internal methods directly, and also for setting up things like callbacks to internal methods (you'll need something like namespace which or namespace code when setting up the callback).
Unlike with the public name, you can delete the internal name command without automatically destroying the object. It'll likely break code (your methods most probably) if you do that, but the base system allows you to do it.
Aside: Tcl 8.7 includes this helper procedure (which also works in 8.6) for creating callback scripts within methods (the funny name means it gets mapped into your methods automatically as callback):
proc ::oo::Helpers::callback {method args} {
list [uplevel 1 {::namespace which my}] $method {*}$args
}
In this case, if the callback was exported, you'd be able to do this instead:
proc ::oo::Helpers::callback {method args} {
list [uplevel 1 self] $method {*}$args
}
but that would be more vulnerable to rename problems. (In all cases, the uplevel 1 is because we want to run a little bit of name-resolving code in the calling context, not inside the scope of the procedure itself.)
I'm not sure how they are implemented, but one reason you'd want to use my is to access non-exported (private) methods. A demo:
oo::class create Foo {
method PrivateMethod {} {puts "this is PrivateMethod"}
method publicMethod {} {puts "this is publicMethod"}
method test {} {
my publicMethod
my PrivateMethod
[self] publicMethod
[self] PrivateMethod
}
}
then:
% Foo create foo
::foo
% foo test
this is publicMethod
this is PrivateMethod
this is publicMethod
unknown method "PrivateMethod": must be destroy, publicMethod or test
my is the mechanism for an object to invoke its methods.
self is the mechanism for introspection on how the current method was called.
Spend some time with the my and self man pages.
I need to modify a parameter named test inside process_data and switch cases outside that function depending on test value.
I couldn't pass it by reference using upvar because the process_data represent a static function for processing received udp packet, and it won't accept more than two parameters 'size and data'.
Also, as far as I found, there is no returned value for the process_data function.
Code:
set test "0"
Agent/UDP instproc process_data {size data} {
//some stuff
if (...)
set test "1"
}
// switch cases depending on test value.
You don't need an extra argument to use upvar if you know the name of the variable you're going to alias. You should be able to do either of these (do not use both):
global test
upvar #0 test test
It's not really classic modular programming, but it will work.
A good place to put the command is at the beginning of the procedure body, like so:
Agent/UDP instproc process_data {size data} {
global test
# some stuff
}
Same thing if you use upvar #0 test test (those two commands are basically equivalent).
Documentation:
global,
upvar
In Kotlin, the function declaration syntax allows you to write equals sign before the curly braces.
Consider these two examples:
Without = sign:
fun foo1() {
println("baz1")
}
The code inside the body gets executed by just calling foo1().
With = sign:
fun foo2() = {
println("baz2")
}
Here, when foo2() is called, nothing happens, but to get the body executed one can write foo2()().
What is the difference in these two declarations and why do they behave differently?
You can run the code using the following program:
fun main() {
foo1()
foo2()
}
/*
This code example produces the following results:
baz1
*/
This question, though having not much meaning, is [intentionally asked and answered by the author][1], because a few questions have already been posted where people got problems because of incorrect function definitions.
Despite visual similarity, the idea of these two declarations is completely different.
1. Function declaration without equals sign
Function declaration without equals sign is a Unit-returning function (similar to Java's void functions).
What's inside the curly braces is its body, which gets executed right on the function call. The function can be rewritten with Unit explicitly specified:
fun foo1(): Unit {
println("baz1")
return Unit
}
Kotlin doesn't require the return statement and explicit return type for Unit-returning functions, and both are usually omitted.
2. Function declaration with equals sign
Function declaration with equals sign is a single-expression function, and what it does is just return what's to the right of equals sign.
A simpler example: fun getInt() = 1 is just a shorter form of fun getInt(): Int { return 1 }.
In foo2, the right hand side is a lambda expression. The code inside the lambda code block is not executed. In other words, foo2 is a function that returns another function.
Return type of foo2 is () -> Unit, a function itself, and thus foo2 is a higher-order function.
Without the syntactic sugar and with explicit type, foo2 can be rewritten as
fun foo2(): () -> Unit {
val result: () -> Unit = { println("baz2") }
return result
}
As to the usage, the function which foo2 returns can be stored in a variable, passed around and can later be invoked:
val f = foo2()
f() //equivalent to
f.invoke()
This is also why foo2()() in the example executes the code from the lambda body.
Alternatively, we can add () at the end when we declare foo2(), as shown in the following example. As such, the lambda expression will be invoked when calling foo3(). But this is not a good pattern.
fun foo3() = {
println("baz3")
}()
A simple question: How do I set the prototype for a function that has not been implemented yet?
I just want to do this, cause I'm referring to a function that does not exist(yet).
In C, we would do something like this:
int foo(int bar);
int myint = foo(1);
int foo(int bar)
{
return bar;
}
How do I do this in Lua (with corona)?
You can't. Amber's comment is correct.
Lua doesn't have a concept of type signatures or function prototypes.
The type of foo is that of the object it contains, which is dynamic, changing at runtime. It could be function in one instant, and string or integer or something else in the next.
Conceptually Lua doesn't have a compilation step like C. When you say "run this code" it starts starts executing instructions at the top and works it's way down. In practice, Lua first compiles your code into bytecode before executing it, but the compiler won't balk at something like this:
greet()
function greet()
print('Hello.')
end
Because the value contained in greet is determined at runtime. It's only when you actually try to call (i.e. invoke like a function) the value in greet, at runtime, that Lua will discover that it doesn't contain a callable value (a function or a table/userdata with a metatable containing a __call member) and you'll get a runtime error: "attempt to call global 'greet' (a nil value)". Where "nil value" is whatever value greet contained at the time the call was attempted. In our case, it was nil.
So you will have to make sure that that the code that creates a function and assigns it to foo is called before you attempt to call foo.
It might help if you recognize that this:
local myint = foo(1)
function foo(bar)
return bar
end
Is syntax sugar for this:
local myint = foo(1)
foo = function(bar)
return bar
end
foo is being assigned a function value. That has to happen before you attempt to call that function.
The most common solution to this problem is to treat the file's function as the "compilation time", that is: declare all of your constant data and functions when the file is executed, ready to be used during "execution time". Then, call a main function to begin the "execution time".
For example:
function main()
greet()
end
function greet()
print('Hello.')
end
main()
As greet has been declared in _G, main can access it.