I'm just learning some Swift and I've come across the section that talks about nesting functions:
Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex.
From here
So if the purported benefit is to "organize the code", why not just have the nested function independently, outside of the outer function? That, to me, seems more organized.
The only benefit I can discern is that you "have access to variables that were declared in the outer function", but this seems trivial in comparison to the messiness of having nested functions.
Any thoughts?
So if the purported benefit is to "organize the code", why not just have the nested function independently, outside of the outer function? That, to me, seems more organized.
Oh, I totally disagree. If the only place where the second function is needed is inside the first function, keeping it inside the first function is much more organized.
Real-life examples here: http://www.apeth.com/swiftBook/ch02.html#_function_in_function
Plus, a function in a function has the local environment in scope. Code inside the nested function can "see" local variables declared before the nested function declaration. This can be much more convenient and natural than passing a bunch of parameters.
However, the key thing that a local function lets you do that you could not readily do in any other way is that you can form the function in real time (because a function is a closure) and return it from the outer function.
http://www.apeth.com/swiftBook/ch02.html#_function_returning_function
One really nice thing is that Xcode will indent nested functions within their parent function in the function pop-up. The function popup is much easier to navigate with functions related to recalculating the layout indented and all grouped in one place.
IMO, the only difference of closures and nested functions is recursion. You can refer the function itself in the function body without a trick.
func a() {
func b() {
b() // Infinite loop!
}
b()
}
Captured reference type object dies when the capturer dies. In this case, capturer is the function's lexical scope. Which means the function is going to die when it finishes its execution.
Technically, this makes a reference-cycle, and usually discouraged. But this can be useful if you use this wisely.
For example, combine this with asynchronous operations.
func spawnAsyncOp1(_ completion: #escaping () -> Void) {
enum Continuation {
case start
case waitForSomethingElse1
case retry
case end
}
let someResource = SomeResource()
func step(_ c: Continuation) {
switch c {
case .start:
return step(.waitForSomethingElse1)
case .waitForSomethingElse1:
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10), execute: {
let fc = (someResource.makeRandomResult() % 100 < 50) ? .end : .retry as Continuation
print("\(fc)")
return step(fc)
})
case .retry:
return step(.start)
case .end:
return completion()
}
}
return step(.start)
}
It can make resource management in a coroutine execution simpler without an explicit object instance. Resources are simply captured in function spawnAsyncOp1 and will be released when the function dies.
Related
There are two functions, say func1 and func2. func2 is an inner function of func1 and based on a condition I wish to return from func1, meaning end execution of func1. How do I do that in kotlin?
fun func1(){
fun func2(){
if(someCondition){
...
return#func1 //How do I do this? since it says return not allowed here
}
}
...
func2()
}
This wouldn't make sense in all cases, as a nested function might outlive the scope of the containing function in some cases. Here's an example of that:
var x: () -> Unit = {}
fun func1() {
fun func2() {}
x = ::func2
}
Here, it would not make sense to allow returns for func1 from func2. By the time x is called, there might not even be an active call to func1. This is basically the topic of non-local returns, which you need inline functions for (see the official documentation). Those, unfortunately, are not available as local functions (at least not yet).
For your specific case, you're probably stuck with signaling that you want a return from func1 by using the return value of func2 and checking for it in func1. (Or an exception, which wouldn't be nice to use for control flow like this.)
In the following code, I'm trying to create a "function pointer" and an array of functions by regarding function names as usual variables:
proc myfunc1() { return 100; }
proc myfunc2() { return 200; }
// a function variable?
var myfunc = myfunc1;
writeln( myfunc() );
myfunc = myfunc2;
writeln( myfunc() );
// an array of functions?
var myfuncs: [1..2] myfunc1.type;
writeln( myfuncs.type: string );
myfuncs[ 1 ] = myfunc1;
myfuncs[ 2 ] = myfunc2;
for fun in myfuncs do
writeln( fun() );
which seems to be working as expected (with Chapel v1.16)
100
200
[domain(1,int(64),false)] chpl__fcf_type_void_int64_t
100
200
So I'm wondering whether the above usage of function variables is legitimate? For creating an array of functions, is it usual to define a concrete function with desired signature first and then refer to its type (with .type) as in the above example?
Also, is it no problem to treat such variables as "usual" variables, e.g., pass them to other functions as arguments or include them as a field of class/record? (Please ignore these latter questions if they are too broad...) I would appreciate any advice if there are potential pitfalls (if any).
This code is using first class function support, which is prototype/draft in the Chapel language design. You can read more about the prototype support in the First-class Functions in Chapel technote.
While many uses of first-class functions work in 1.16 and later versions, you can expect that the language design in this area will be revisited. In particular there isn't currently a reasonable answer to the question of whether or not variables can be captured (and right now attempting to do so probably results in a confusing error). I don't know in which future release this will change, though.
Regarding the myfunc1.type part, the section in the technote I referred to called "Specifying the type of a first-class function" presents an alternative strategy. However I don't see any problem with using myfunc1.type in this case.
Lastly, note that the lambda support in the current compiler actually operates by creating a class with a this method. So you can do the same - create a "function object" (to borrow a C++ term) - that has the same effect. A "function object" could be a record or a class. If it's a class, you might use inheritance to be able to create an array of objects that can respond to the same method depending on their dynamic type. This strategy might allow you to work around current issues with first class functions. Even if first-class-function support is completed, the "function object" approach allow you to be more explicit about captured variables. In particular, you might store them as fields in the class and set them in the class initializer. Here is an example creating and using an array of different types of function objects:
class BaseHandler {
// consider these as "pure virtual" functions
proc name():string { halt("base name called"); }
proc this(arg:int) { halt("base greet called"); }
}
class HelloHandler : BaseHandler {
proc name():string { return "hello"; }
proc this(arg:int) { writeln("Hello ", arg); }
}
class CiaoHandler : BaseHandler {
proc name():string { return "ciao"; }
proc this(arg:int) { writeln("Ciao ", arg); }
}
proc test() {
// create an array of handlers
var handlers:[1..0] BaseHandler;
handlers.push_back(new HelloHandler());
handlers.push_back(new CiaoHandler());
for h in handlers {
h(1); // calls 'this' method in instance
}
}
test();
Yes, in your example you are using Chapel's initial support for first-class functions. To your second question, you could alternatively use a function type helper for the declaration of the function array:
var myfuncs: [1..2] func(int);
These first-class function objects can be passed as arguments into functions – this is how Futures.async() works – or stored as fields in a record (Try It Online! example). Chapel's first-class function capabilities also include lambda functions.
To be clear, the "initial" aspect of this support comes with the caveat (from the documentation):
This mechanism should be considered a stopgap technology until we have developed and implemented a more robust story, which is why it's being described in this README rather than the language specification.
When to use functioneExpression rather than function declaration in Go?
I searched Function Expression vs Function Declaration (in JS), it's about hoisting. How about Golang?
There is one unique property to each:
A function declaration binds an identifier, the function name, to a function; so the function name will be an identifier which you can refer to.
A function literals represents an anonymous function. Function literals are closures, they capture the surrounding environment: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.
Don't be deluded: syntactically whenever a function literal is used, a declared function could also be used. For example the following code is a valid and working Go code:
func do() {}
func main() {
go do()
defer do()
}
The answer to when to use one over the other lies in the unique properties listed above.
Use function declaration when you want to refer to the function, when you want to reuse it. This is also a good way to separate code, function declaration must be at the file level: you can't declare a function in another function. See Golang nested class inside function for details.
Use function literals when you want the function to have access to the local variables and other identifiers surrounding it. Since you can't declare a function in another function, to capture the local variables and identifiers, the only option here is a function literal (unless you want to pass everything as arguments to a declared function, which could quickly get dirty if the function needs to modify the values in which case they need to be "transformed" into pointers and addresses need to be passed). For an interesting related question, check out Define a recursive function within a function in Go.
When the function does not need to have a name, and the function does not need access to the local variables, you may choose which one to use, relying on your judgement, examples seen in other (quality) projects and prior experiences. If the function body is "small", easier / simpler to use a function literal. If the function body is "big", code will be easier to read and understand if you declare it as a separate function and provide sufficient documentation to it.
An interesting / related topic is a variable of function type, which you may initialize using either a function literal or with a declared function. It has the benefits that it is an identifier so you can refer to it, and that its value can be changed and a new function can be assigned to it.
For example:
func do() { fmt.Println("Doing...") }
var f = do
func main() {
f()
f = func() { fmt.Println("Not doing!") }
f()
}
Output of the above (try it on the Go Playground):
Doing...
Not doing!
Very useful for mocking functions in tests. For an example, see Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls).
Anonymous functions in Go are used in various situations:
- to start a goroutine
go func() {
// body
}()
- with a defer statement
defer func() {
// body
}()
- as an argument to another function
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
// todo
})
- as a closure (examples)
Function declarations are used when you want to refer to the function by name. Maybe to call it from multiple places in your own code, or to expose it to other packages.
I have 2 general questions about function programming.
Consider the following 3 functions:
result = fun3(fun2(fun1(param1))); // param4
function fun1(param1) {
// ...
return param2;
}
function fun2(param2) {
// ...
return param3;
}
function fun3(param3) {
// ...
return param4;
}
Each function expects 1 parameter, does some computation and returns a variable.
In my case, every subsequent function relies on the output of the preceding function.
Is the solution in my example a common practice? Or are there better ways?
What if a function produces 2 outputs and 2 different functions need them?
Like in this example:
function fun1(param1) {
// ...
return param2, param3;
}
function fun2(param2) {
// ...
return param4;
}
function fun3(param3) {
// ...
return param5;
}
PS: Although this is a general programming questions, maybe it could be important to mention, that I use PHP.
The answer to the first question is that, yes, it's a very common technique in functional programming. It is, for example, the basis of currying which is also very common.
As regards the second question, many functional languages support the concept of a tuple or heterogeneous list - if you want to return multiple values you either explicitly create one or the runtime generates one for you on the fly. Sending return values into multiple subsequent functions would be done with the aid of a helper function which does the multiplexing. The question becomes how you handle the return values from those functions, presumably as a list I guess. It might depend on your use case.
In Python that might look like
def multiplex(functions, value):
return [func(value) for func in functions]
To keep with your single-argument style the above might end up being curried in some fashion so that the list of functions to multiplex to are bound in a separate function application. Different languages achieve that in different ways, Python has a functools module which supports partial application of a function whereas Scala natively supports partially applying a function.
I am registering listeners from JS to NPAPI plugin.
In order not to register same listener multiple times I need a way to compare passed NPVariant object to those already in the list.
This is how I'm registering listeners from JS :
PluginObject.registerListener("event", listener);
and then in plugin source :
for (l=head; l!=NULL; l=l->next) {
// somehow compare the listeners
// l->listener holds NPVariant object
if (l->listener-> ??? == new_lle->listener-> ???)
{
found = 1;
DBG("listener is a duplicate, not adding.");
NPN_MemFree(new_lle->listener);
free(new_lle);
break;
}
}
when you're talking about a javascript function the NPVariant is just an NPObject.
typedef struct _NPVariant {
NPVariantType type;
union {
bool boolValue;
int32_t intValue;
double_t doubleValue;
NPString stringValue;
NPObject *objectValue;
} value;
} NPVariant;
compare the val.type and val.objectValue. This will usually work, but if it doesn't there isn't another way so you're still better off trying it. I guess one other possibility would be to create a javascript function to compare them, inject it with NPN_Evaluate and call it with the two objects.
I don't think you can rely on objectValue. For instance if you do the following:
foo={};
bar=foo;
x={};
x.f=foo; x.b=bar;
Now, if you call NPN_Enumerate and pass x as the NPObject, you get two identifiers. Calling GetProperty for each of these returns NPVariants, but the value of variant->value.objectValue will be different for each, and different again in subsequent calls to NPN_Enumerate.
taxilian: is there significant overhead in calling NPN_Invoke with the two NPObjects, just to test for equality? This also involves some calls to GetProperty and the creation of identifiers and calling the NPVARIANT macros to test the results, etc.. I am wondering just how much logic I should be injecting and evaluating in Javascript.. this code injection seems to come up as a solution again and again. Is it costly?