Passing arguments to multiple functions - function

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.

Related

Function variable and an array of functions in Chapel

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.

How to turn a Ceylon Sequential or array into a generic Tuple with the appropriate type?

I've got a generic function that needs to create a Tuple to call a function whose arguments I don't know the types of.
Something like this (except array in this example is created by some external code, so I can't just apply the function directly):
Result apply<Result, Where>(
Anything[] array,
Callable<Result, Where> fun)
given Where satisfies Anything[] => nothing;
Is there a type-safe way to implement this method and get the function to be called with the given arguments?
This cannot be done completely type-safely... but assuming that the array indeed contains elements of the correct types as they should appear in a Tuple of type Where, the following function will do the trick:
Tuple<Anything, Anything, Anything> typedTuple({Anything+} array) {
if (exists second = array.rest.first) {
return Tuple(array.first, typedTuple({ second }.chain(array.rest.rest)));
}
else {
return Tuple(array.first, []);
}
}
And apply gets implemented as:
Result apply<Result, Where>(
[Anything+] array,
Callable<Result, Where> fun)
given Where satisfies Anything[] {
value tuple = typedTuple(array);
assert(is Where tuple);
return fun(*tuple);
}
There's nothing relating the type of array to the parameters of fun, so that signature can't possibly be implemented in a type-safe way. You're not constraining the type of array at all; it could contain anything. How in principle would a type-safe implementation handle the case where fun expects [String, Integer] but array is [Boolean+]?

What is the benefit of nesting functions (in general/in Swift)

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.

How to compare NPVariant objects?

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?

What's the cleanest way to simulate pass-by-reference in Actionscript 3.0?

Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this?
For example, is there a clean way to implement swap( intA, intB ) in Actionscript?
I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object:
function swapAB(aValuesContainer:Object):void
{
if (!(aValuesContainer.hasOwnProperty("a") && aValuesContainer.hasOwnProperty("b")))
throw new ArgumentError("aValuesContainer must have properties a and b");
var tempValue:int = aValuesContainer["a"];
aValuesContainer["a"] = aValuesContainer["b"];
aValuesContainer["b"] = tempValue;
}
var ints:Object = {a:13, b:25};
swapAB(ints);
I suppose an alternative would be somewhere defining this sort of thing ...
public class Reference {
public var value:*;
}
Then use functions that take some number of Reference arguments to act as "pointers" if you're really just looking for "out" parameters and either initialize them on the way in or not and your swap would become:
function swap(Reference a, Reference b) {
var tmp:* = a.value;
a.value = b.value;
b.value = tmp;
}
And you could always go nuts and define specific IntReference, StringReference, etc.
This is nitpicking, but int, String, Number and the others are passed by reference, it's just that they are immutable. Of course, the effect is the same as if they were passed by value.
You could also use a wrapper instead of int:
public class Integer
{
public var value:int;
public function Integer(value:int)
{
this.value = value;
}
}
Of course, this would be more useful if you could use operator overloading...
Just look at some Java code. Java has had the convention that reference types are passed by reference and primitive types are passed by value since it's inception. It's a very good model in many ways.
But talking about swap, the best and easiest way to do a swap in Java/AS3 is with the following three lines:
var temp:int = array[i];
array[j] = array[i];
array[i] = temp;
Theres not really any reason to use a function to do a simple swap, when you can do it faster with just 3 lines.
It is annoying. But if you use different idioms than in e.g. C#, you can get reasonable-quality results. If you need to pass a lot of parameters back and forth, pass in an object filled with the needed data, and change the object's parameters when you return. The Object class is for just this sort of thing.
If you just need to return a bunch of data, return an Object. This is more in keeping with the ECMAScript style than pass-by-ref semantics.
Destructuring assignment (e.g. [a,b] = [b,a]) isn't defined in the ECMA-262 3 specification, and it's not implemented in JavaScript 1.5, which is the version equivalent to the JScript implementation in IE. I've seen this syntax in the AS4 specifications preview though, and I believe it's part of JavaScript 1.7.
If ActionScript works like Javascript,
[a,b] = [b,a]