Inside a function, how do I construct a new function based on original function parameters, in order to pass as an argument to another function - performance

I'm having trouble with function declarations and scope in julia. I have a main function, let's call it mainfunc which accepts some arguments. Within this function, I would ultimately like to call a different function, say callfunc, which takes a function as an argument. This function I will call passfunc.
One further complication I have is that there is a final function which I define outside of the logic which depends on the arguments but still depends on the arguments in a different way. I can call this initfunc. This must be composed with some other function, depending on the arguments, to create passfunc.
Based on the arguments given to mainfunc, I will have different definitions of passfunc. Given the answer I got to a related question here, I initially tried to define my function logic in the following way, using anonymous functions which are apparently more efficient:
function mainfunc(args)
init_func = x -> funcA(x, args)
if args[1] == "foo"
anon_func = x -> func1(x, args)
elseif args[1] == "bar"
anon_func = x -> func2(x, args)
end
function passfunc(x)
return init_func(x) + anon_func(x)
end
# ... define other args...
callfunc(passfunc, other_args)
end
Defining my function in this way leads to errors in julia - apparently passfunc is an undefined variable when I run this code. Does the scope not allow the anonymous functions to be defined in the if statements? How else could I write code that achieves this?
I feel like a better understanding of functional programming principles would make the solution here obvious. Thank you in advance for any tips you can offer on improving this.
Also, I am running this with julia v0.7

Related

defining function using var vs function

exported:
var MyFunction = func(){}
function MyFunction func(){}
unexported:
var myFunction = func(){}
function myFunction func(){}
I read the var functionName = function() {} vs function functionName() {} this is about Javascript.
The reason I am considering changing from function myFunction func(){} to var myFunction = func(){} is the later makes me easier to do my unit test.
So I am wondering if there's anything I need to pay attention to before making this change.
The chief distinction between the two forms is that they differ not only in syntax but rather in their semantics:
The "normal" form which uses the func name (...) form
creates a regular named function.
What you call "create a function using var" is actually creating a so-called anonymous function and assigning its value to a variable.
The difference is that in Go, anonymous functions behave as closures, while regular functions do not.
A closure is a function which "captures" any variables from its outer lexical scope which are used in the function's body (while not being shadowed by local variables and function arguments there).
The distinction may not be apparent when either form it used at the top level of a package — that is, outside of any function's body, — since the outer scope in this case is the package's global variables, but inside other functions the distinction is apparent: the "normal" form simply cannot be used.
Other distinction is that you can replace the value in a variable containing a function value, while you cannot do the same with the normal function.
Still, if we're talking about the top-level code, the suggestion offered by Flimzy holds: in production Go code, having global variables containing function values is code smell until it can be proved to be otherwise.

Scala -> Ruby conversion: Confusing output

Ruby Code:
def fnAdd(x)
return ->(y) { x + y }
end
add1 = 1.method(:fnAdd)
puts add1.call(10)
Output: Proc:0x007f52658d3330#main.rb:2 (lambda)
I am having issues getting the desired output in the above code.
I'm basically trying to write the following Scala code (which calls a function that returns another function) in Ruby.
Scala Code:
def fnAdd (x:Int) = {
(y:Int) => x + y
}
var add1 = fnAdd (1)
var add2 = fnAdd (2)
println(add1(10))
println(add2(3))
Output: 11 5
I've made an attempt at converting the code to Ruby but I'm not sure if it is correct. I don't understand the output, which appears to be some kind of proc object.
Could someone please explain what I need to change to get the desired output?
I'm not sure how your first example is even running, as it produces a NameError on my machine. Regardless, #method is intended for accessing methods on specific objects. You've defined a standalone method which is already curried, not one inside of the Fixnum class. So you simply need to call it as a method.
add1 = fnAdd(1)
Also, Ruby has the same behavior as Scala with regard to returning the last expression in a method, so you don't need to use return in this case.
Edit:
Thanks to #JörgWMittag for pointing out a few flaws here. Defining #fnAdd at the top-level makes it a private instance method on Object. Since everything in Ruby is an object, Fixnum inherits from the Object class. Thus, 1.method(:fnAdd) is simply giving you the fnAdd method without actually passing it any arguments. Thus, it still expects to be called twice.
fnAddMethod = 1.method(:fnAdd)
add1 = fnAddMethod.call(1)
puts add1.call(10)
However, this would be extremely unidiomatic, so it's best to stick with the simpler solution.

What does it mean to pass `_` (i.e., underscore) as the sole parameter to a Dart language function?

I'm learning Dart and see the following idiom a lot:
someFuture.then((_) => someFunc());
I have also seen code like:
someOtherFuture.then(() => someOtherFunc());
Is there a functional difference between these two examples?
A.k.a., What does passing _ as a parameter to a Dart function do?
This is particularly confusing given Dart's use of _ as a prefix for declaring private functions.
It's a variable named _ typically because you plan to not use it and throw it away. For example you can use the name x or foo instead.
The difference between (_) and () is simple in that one function takes an argument and the other doesn't.
DON’T use a leading underscore for identifiers that aren’t private.
Exception: An unused parameter can be named _, __, ___, etc. This
happens in things like callbacks where you are passed a value but you
don’t need to use it. Giving it a name that consists solely of
underscores is the idiomatic way to indicate the value isn’t used.
https://dart.dev/guides/language/effective-dart/style
An underscore (_) is usually an indication that you will not be using this parameter within the block. This is just a neat way to write code.
Let's say I've a method with two parameters useful and useless and I'm not using useless in the code block:
void method(int useful, int useless) {
print(useful);
}
Since useless variable won't be used, I should rather write the above code as:
void method(int useful, int _) { // 'useless' is replaced with '_'
print(useful);
}
From the Dart Doc - PREFER using _, __, etc. for unused callback parameters.
Sometimes the type signature of a callback function requires a
parameter, but the callback implementation doesn't use the
parameter. In this case, it's idiomatic to name the unused parameter
_. If the function has multiple unused parameters, use additional
underscores to avoid name collisions: __, ___, etc.
futureOfVoid.then((_) {
print('Operation complete.');
});
This guideline is only for functions that are both anonymous and
local. These functions are usually used immediately in a context
where it's clear what the unused parameter represents. In contrast,
top-level functions and method declarations don't have that context,
so their parameters must be named so that it's clear what each
parameter is for, even if it isn't used.
Copy paste the following code in DartPad and hit Run -
void main() {
Future.delayed(Duration(seconds: 1), () {
print("No argument Anonymous function");
});
funcReturnsInteger().then((_) {
print("Single argument Anonymous function " +
"stating not interested in using argument " +
"but can be accessed like this -> $_");
});
}
Future<int> funcReturnsInteger() async {
return 100;
}
That expression is similar to "callbacks" in node.js, the expression have relation to async task.
First remember that => expr expression is shorthand for {return *expr*}, now in someFuture.then((_) => someFunc()), someFuture is a variable of type Future, and this keeps your async task, with the .then method you tell what to do with your async task (once completed), and args in this method you put the callback ((response) => doSomethingWith(response)).
You learn more at Future-Based APIs and Functions in Dart. Thanks
Very common use, is when we need to push a new route with Navigator but the context variable in the builder is not going to be used:
// context is going to be used
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => NewPage(),
));
// context is NOT going to be used
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => NewPage(),
));
I think what people are confusing here is that many think the _ in
someFuture.then((_) => someFunc());
is a parameter provided to the callback function which is wrong, its actually a parameter passed back from the function that you can give a name that you want (except reserved keywords of course), in this case its an underscore to show that the parameter will not be used. otherwise, you could do something like in example given above:((response) => doSomethingWith(response))

what does "()" in programming mean? As an example: getche() I understand what getche does, but why the () at the end?

As an example: getche() I understand what getche does, but why the () at the end?
If you are not putting anything in the parenthesis, why do you need them to be there? Just because of standards?
Thanks
Whether a function/method call needs to have parentheses at the end is a syntax particularity that varies from language to language. In Ruby, for example, you don't need it, while in Java, you do.
The compiler can use it to determine that you're making a function/method call. In many languages, you can reference a function as an object, so you need the parentheses to distinguish a reference to a function from a call to a function.
For example, in javascript:
function something(){
return "hello";
}
var a = something;
var b = something();
The variable a will contain the actual function something, while the variable b will contain "hello".
It executes the function without passing any parameters.
In languages with first-class functions, foo and foo() have different meanings. Consider these two examples, in Lua:
local bar = foo -- Assigns foo to bar. bar is now the function at foo.
local bar = foo() -- Executes foo, and assigns the return value to bar.
This, of course, depends on the language you are using. For example, in Haskell, no parenthesis are used to call functions.
This is syntax for Method/function.
Why is the need of it ? Because in the () you can provide the input arguments as well.
like for example :
var sum = addition(3,4);
Here addition can be defined as:
int addition(int a, int b)
{
return (a+b);
}

Defining Lua methods as initialization

In the Lua language, I am able to define functions in a table with something such as
table = { myfunction = function(x) return x end }
I wondered if I can created methods this way, instead of having to do it like
function table:mymethod() ... end
I am fairly sure it is possible to add methods this way, but I am unsure of the proper name of this technique, and I cannot find it looking for "lua" and "methods" or such.
My intention is to pass a table to a function such as myfunction({data= stuff, name = returnedName, ?method?init() = stuff}).
Unfortunately I have tried several combinations with the colon method declaration but none of them is valid syntax.
So...anyone here happens to know?
Sure: table:method() is just syntactic sugar for table.method(self), but you have to take care of the self argument. If you do
tab={f=function(x)return x end }
then tab:f(x) won't work, as this actually is tab.f(tab,x) and thus will return tab instead of x.
You might take a look on the lua users wiki on object orientation or PiL chapter 16.

Resources