Passing a function as an argument into another function won't compile without using quotes ''? - function

When I pass a function (let's call it f) into my Base function , the Base function doesn't recognize
the f function , without using '' quotes , here's the code :
function y = test(a, b, n ,f)
if ( rem(n,2) ~= 0 )
error ( 'n is not even' )
end
% create a vector of n+1 linearly spaced numbers from a to b
x = linspace ( a, b, n+1 );
for i = 1:n+1
% store each result at index "i" in X vector
X(i) = feval ( f, x(i) );
end
y=sum(X);
end
And this is f.m :
function [y] = f (x)
y = 6-6*x^5;
When I run from command line with quotes :
>> [y] = test(0,1,10,'f')
y =
52.7505
but when I remove them :
>> [y] = test(0,1,10,f)
Error using f (line 2)
Not enough input arguments.
Where is my mistake ? why can't I execute [y] = test(0,1,10,f) ?
Thanks

The function feval expects either the function name (i.e., a string) or a function handle as input. In your code, f is neither a name, nor a handle. Use either the string 'f' or the handle #f when calling your base function test.
If, as posted in the comments, function handles are not allowed per assignment in the call to the base function, you can still use the function handle to create a string with the name of the function. This functionality is provided by the function func2str:
functionName = func2str(#f);
test(0,1,10,functionname);

Try passing #f as the argument instead of 'f', and also change the line to
X(i) = f(x(i));
The thing is that just f is not a function handle. Also there's no need to use feval in this case.

Related

Evaluate function stored in Matlab cell array

I have a function called objective in Matlab I evaluate by writing [f, df] = objective(x, {#fun1, #fun2, ..., #funN}) in a script. The functions fun1, fun2, ..., funN have the format [f, df] = funN(x).
Inside objective I want to, for each input in my cell array called fun, evaluate the given functions using the Matlab built-in function feval as:
function [f, df] = objective(x, fun)
f = 0;
df = 0;
for i = 1:length(fun)
fhandle = fun(i);
[fi, dfi] = feval(fhandle, x);
f = f + fi;
df = df + dfi;
end
end
I get the following error evaluating my objective.
Error using feval
Argument must contain a string or function_handle.
I do not get how to come around this error.
You need to reference the elements of fun using curly braces
fhandle = fun{i};
PS
It is better not to use i and j as variable names in Matlab
Alternatively, a solution using cellfun.
A more elegant approach using cellfun
function [f df] = objective( x, fun )
[f, df] = cellfun( #(f) f(x), fun );
f = sum(f);
df = sum(df);
Note the kinky use of cellfun - the cellarray is the fun rather than the data ;-)

Want to use a vector as parameter to a function, without having to separate its elements

If I call a matlab function with:
func(1,2,3,4,5)
it works perfectly.
But if I do:
a=[1,2,3,4,5] %(a[1;2;3;4;5] gives same result)
then:
func(a)
gives me:
??? Error ==> func at 11
Not enough input arguments.
Line 11 in func.m is:
error(nargchk(5, 6, nargin));
I notice that this works perfectly:
func(a(1),a(2),a(3),a(4),a(5))
How can I use the vector 'a' as a parameter to a function? I have another function otherfunc(b) which returns a, and would like to use its output as a paramater like this func(otherfunc(b)).
Comma-seperated lists
(CSL) can be passed to functions as parameter list,
so what you need is a CSL as 1,2,3,4,5 constructed from an array.
It can be generated using cell array like this:
a=[1,2,3,4,5];
c = num2cell(a);
func(c{:});
Maybe you could try with nargin - a variable in a function that has the value of the number of input arguments. Since you have a need for different length input, I believe this can best be handled with varargin, which can be set as the last input variable and will then group together all the extra input arguments..
function result = func(varargin)
if nargin == 5: % this is every element separately
x1 = varargin{1}
x2 = varargin{2}
x3 = varargin{3}
x4 = varargin{4}
x5 = varargin{5}
else if nargin == 1: % and one vectorized input
[x1 x2 x3 x4 x5] = varargin{1}
I've written x1...x5 for your input variables
Another method would be to create a separate inline function. Say you have a function f which takes multiple parameters:
f = f(x1,x2,x3)
You can call this with an array of parameter values by defining a separate function g:
g = #(x) f(x(1),x(2),x(3))
Now, if you have a vector of parameters values v = [1,2,3], you will be able to call f(v(1),v(2),v(3)) using g(v).
Just make the function take a single argument.
function result = func(a)
if ~isvector(a)
error('Input must be a vector')
end
end
Since arguments to functions in Matlab can themselves be vectoes (or even matrices) you cannot replace several arguments with a single vector.
If func expects 5 arguments, you cannot pass a single vector and expect matlab to understand that all five arguments are elements in the vector. How can Matlab tell the difference between this case and a case where the first argument is a 5-vector?
So, I would suggest this solution
s.type = '()';
s.subs = {1:5};
func( subsref( num2cell( otherfunc(b) ), s ) )
I'm not sure if this works (I don't have matlab here), but the rationale is to convert the 5-vector a (the output of otherfunc(b)) into a cell array and then expand it as 5 different arguments to func.
Please not the difference between a{:} and a(:) in this subsref.
You could create a function of the following form:
function [ out ] = funeval( f, x )
string = 'f(';
for I = 1:length(x)
string = strcat( string, 'x(' , num2str(I), '),' );
end
string( end ) = ')';
out = eval( string );
end
In which case, funeval( func, a ) gives the required output.
Use eval:
astr = [];
for i=1:length(a)
astr = [astr,'a(',num2str(i),'),']; % a(1),a(2),...
end
astr = astr(1:end-1);
eval(['func(' astr ');']);

OCaml - How do I create a function with a function as output?

"Write a function lv: cfg -> (blabel -> ide set), which computes the live variables analysis on the given control flow graph."
Having cfg and blabel defined and ide set as a list of string, how can I create a function with that signature?
You're presumably familiar with the let syntax to define a function:
let f x = x + 1 in …
You can use this syntax anywhere, including in a function body. Now if you happen to use the inner function's name as the return value of the outer function, the outer function will be returning a function.
let outer_function x =
let inner_function y = x + y in
inner_function
The let syntax is in fact syntactic sugar for fun or function. In particular, if you define inner_function just to use the name once, you might as well use the fun notation and not bother giving the inner function a name.
let outer_function x =
fun y -> x + y
Furthermore, if all the outer function does when you pass it an argument is to build and return an inner function, then consider its behavior when you pass that function two arguments. First the outer function builds an inner function, using its first (and only) argument; then that inner function is applied to the second argument, so its body is executed. This is equivalent to having just one function that takes two arguments. This
observation is known as currying.
let outer_function x y = x + y
Note that the type of this function is int -> int -> int; this is the same type as int -> (int -> int) (the arrow type operator is right-associative).
Currying doesn't apply when the outer function does some work before building the inner function. In that case, the work is performed after receiving the first argument.
let outer_function x =
print_endline "outer";
fun y -> print_endline "inner"; x + y
So the structure of your code is likely to look like this:
let lv (c : cfg) : blabel -> ide set =
let c' = do_some_precomputation c in
fun (bl : blabel) -> (… : ide set)

How to alias a function name in Fortran

Not sure if the title is well put. Suggestions welcome.
Here's what I want to do. Check a condition, and then decide which function to use in a loop. For example:
if (a < 0) then
loop_func = func1
else
loop_func = func2
endif
I can then use loop_func as a pointer when writing my loop. Both functions take exactly the same inputs, and are different approaches on tackling the problem based on the value of a. This will allow me to only have one block of code, instead of two nearly identical blocks. This could apply to subroutines too.
Any ideas how this might be implemented?
Thank you.
Yes, Fortran has procedure pointers, so you can in effect alias a function name. Here is a code example which assigns to the function pointer "f_ptr" one function or the other. Thereafter the program can use "f_ptr" and the selected function will be invoked.
module ExampleFuncs
implicit none
contains
function f1 (x)
real :: f1
real, intent (in) :: x
f1 = 2.0 * x
return
end function f1
function f2 (x)
real :: f2
real, intent (in) :: x
f2 = 3.0 * x**2
return
end function f2
end module ExampleFuncs
program test_func_ptrs
use ExampleFuncs
implicit none
abstract interface
function func (z)
real :: func
real, intent (in) :: z
end function func
end interface
procedure (func), pointer :: f_ptr => null ()
real :: input
write (*, '( / "Input test value: ")', advance="no" )
read (*, *) input
if ( input < 0 ) then
f_ptr => f1
else
f_ptr => f2
end if
write (*, '(/ "evaluate function: ", ES14.4 )' ) f_ptr (input)
stop
end program test_func_ptrs
Most Fortran implementations do not have a standard way to manipulate function pointers or procedure pointers. However, Fortran 2003 and later have something. (See page 6 of this.)
For the given situation, this will work pretty well in its place:
function func1 (p1, p2, etc)
... as you have it already
end
function func2 (p1, p2, etc)
... as you have it already
end
function funcselect (a, p1, p2, etc)
if (a < 0) then
x = func1 (p1, p2, etc)
else
x = func2 (p1, p2, etc)
endif
end
Then just call funcselect with the extra parameter instead of what you would have done with loop_func.

Define default values for function arguments

In the Lua wiki I found a way to define default values for missing arguments:
function myfunction(a,b,c)
b = b or 7
c = c or 5
print (a,b,c)
end
Is that the only way? The PHP style myfunction (a,b=7,c=5) does not seem to work. Not that the Lua way doesn't work, I am just wondering if this is the only way to do it.
If you want named arguments and default values like PHP or Python, you can call your function with a table constructor:
myfunction{a,b=3,c=2}
(This is seen in many places in Lua, such as the advanced forms of LuaSocket's protocol modules and constructors in IUPLua.)
The function itself could have a signature like this:
function myfunction(t)
setmetatable(t,{__index={b=7, c=5}})
local a, b, c =
t[1] or t.a,
t[2] or t.b,
t[3] or t.c
-- function continues down here...
end
Any values missing from the table of parameters will be taken from the __index table in its metatable (see the documentation on metatables).
Of course, more advanced parameter styles are possible using table constructors and functions- you can write whatever you need. For example, here is a function that constructs a function that takes named-or-positional argument tables from a table defining the parameter names and default values and a function taking a regular argument list.
As a non-language-level feature, such calls can be changed to provide new behaviors and semantics:
Variables could be made to accept more than one name
Positional variables and keyword variables can be interspersed - and defining both can give precedence to either (or cause an error)
Keyword-only positionless variables can be made, as well as nameless position-only ones
The fairly-verbose table construction could be done by parsing a string
The argument list could be used verbatim if the function is called with something other than 1 table
Some useful functions for writing argument translators are unpack (moving to table.unpack in 5.2), setfenv (deprecated in 5.2 with the new _ENV construction), and select (which returns a single value from a given argument list, or the length of the list with '#').
In my opinion there isn't another way. That's just the Lua mentality: no frills, and except for some syntactic sugar, no redundant ways of doing simple things.
Technically, there's b = b == nil and 7 or b (which should be used in the case where false is a valid value as false or 7 evaluates to 7), but that's probably not what you're looking for.
The only way i've found so far that makes any sense is to do something like this:
function new(params)
params = params or {}
options = {
name = "Object name"
}
for k,v in pairs(params) do options[k] = v end
some_var = options.name
end
new({ name = "test" })
new()
If your function expects neither Boolean false nor nil to be passed as parameter values, your suggested approach is fine:
function test1(param)
local default = 10
param = param or default
return param
end
--[[
test1(): [10]
test1(nil): [10]
test1(true): [true]
test1(false): [10]
]]
If your function allows Boolean false, but not nil, to be passed as the parameter value, you can check for the presence of nil, as suggested by Stuart P. Bentley, as long as the default value is not Boolean false:
function test2(param)
local default = 10
param = (param == nil and default) or param
return param
end
--[[
test2(): [10]
test2(nil): [10]
test2(true): [true]
test2(false): [false]
]]
The above approach breaks when the default value is Boolean false:
function test3(param)
local default = false
param = (param == nil and default) or param
return param
end
--[[
test3(): [nil]
test3(nil): [nil]
test3(true): [true]
test3(false): [false]
]]
Interestingly, reversing the order of the conditional checks does allow Boolean false to be the default value, and is nominally more performant:
function test4(param)
local default = false
param = param or (param == nil and default)
return param
end
--[[
test4(): [false]
test4(nil): [false]
test4(true): [true]
test4(false): [false]
]]
This approach works for reasons that seem counter-intuitive until further examination, upon which they are discovered to be kind of clever.
If you want default parameters for functions that do allow nil values to be passed, you'll need to do something even uglier, like using variadic parameters:
function test5(...)
local argN = select('#', ...)
local default = false
local param = default
if argN > 0 then
local args = {...}
param = args[1]
end
return param
end
--[[
test5(): [false]
test5(nil): [nil]
test5(true): [true]
test5(false): [false]
]]
Of course, variadic parameters completely thwart auto-completion and linting of function parameters in functions that use them.
Short answer is that it's simplest and best way . in lua , variables by default equal with nil . this means if we don't pass argument to lua functions ,the argument is exits but is nil and lua programmers uses of this lua attribute for set the default value .
also it's not a way for set default value but you can use following function
this function create a error is you don't pass values to arguments
function myFn(arg1 , arg2)
err = arg1 and arg2
if not err then error("argument") end
-- or
if not arg1 and arg2 then error("msg") end
but it's not a good way and better is don't use of this function
and in diagrams shows optional argument in [,arg]
function args(a1 [,a2])
-- some
end
function args ( a1 [,a2[,a3]])
-- some
end
As always, "Lua gives you the power, you build the mechanisms". The first distinction to make here is that between named parameters and the commonly used parameter list.
The parameter list
Assuming all your args are given in the parameter list as follows, they will all be initialized. At this point, you can't distinguish between "wasn't passed" and "was passed as nil" - both will simply be nil. Your options for setting defaults are:
Using the or operator if you expect a truthy value (not nil or false). Defaulting to something even if false is given might be a feature in this case.
Using an explicit nil check param == nil, used either as if param == nil then param = default end or the typical Lua ternary construct param == nil and default or param.
If you find yourself frequently repeating the patterns from point (2), you might want to declare a function:
function default(value, default_value)
if value == nil then return default_value end
return value
end
(whether to use global or local scope for this function is another issue I won't get into here).
I've included all three ways the following example:
function f(x, y, z, w)
x = x or 1
y = y == nil and 2 or y
if z == nil then z == 3 end
w = default(w, 4
print(x, y, z, w)
end
f()
f(1)
f(1, 2)
f(1, 2, 3)
f(1, 2, 3, 4)
note that this also allows omitting arguments inbetween; trailing nil arguments will also be treated as absent:
f(nil)
f(nil, 2, 3)
f(nil, 2, nil, 4)
f(1, 2, 3, nil)
Varargs
A lesser known feature of Lua is the ability to actually determine how many arguments were passed, including the ability to distinguish between explicitly passed nil arguments and "no argument" through the select function. Let's rewrite our function using this:
function f(...)
local n_args = select("#", ...) -- number of arguments passed
local x, y, z, w = ...
if n_args < 4 then w = 4 end
if n_args < 3 then z = 3 end
if n_args < 2 then y = 2 end
if n_args < 1 then x = 1 end
print(x, y, z, w)
end
f() -- prints "1 2 3 4"
f(nil) -- prints "nil 2 3 4"
f(1, nil) -- prints "1 nil 3 4"
f(1, nil, 3) -- prints "1 nil 3 4"
f(nil, nil, nil, nil) -- prints 4x nil
Caveat: (1) the argument list got dragged into the function, hurting readability (2) this is rather cumbersome to write manually, and should probably be abstracted away, perhaps time using a wrapper function wrap_defaults({1, 2, 3, 4}, f) that supplies the defaults as appropriate. Implementation of this is left up to the reader as an exercise (hint: the straightforward way would first collect the args into a garbage table, then unpack that after setting the defaults).
Table calls
Lua provides syntactic sugar for calling functions with a single table as the only argument: f{...} is equivalent to f({...}). Furthermore, {f(...)} can be used to capture a vararg returned by f (caveat: if f returns nils, the table will have holes in it's list part).
Tables also allow implementing named "arguments" as table fields: Tables allow mixing a list and a hash part, making f{1, named_arg = 2} perfectly valid Lua.
In terms of limitations, the advantage of table call is that it only leaves a single argument - the table - on the stack rather than multiple arguments. For recursive functions, this allows hitting the stack overflow later. Since PUC Lua drastically increased the stack limit to ~1M this isn't much of an issue anymore; LuaJIT still has a stack limit of ~65k however, and PUC Lua 5.1 is even lower at around 15k.
In terms of performance & memory consumption, the table call is obviously worse: It requires Lua to build a garbage table, which will then waste memory until the GC gets rid of it. Garbage parameter tables should therefore probably not be used in hotspots where plenty of calls happen. Indexing a hashmap is also obviously slower than getting values straight off the stack.
That said, let's examine the ways to implement defaults for tables:
Unpacking / Destructuring
unpack (table.unpack in later versions (5.2+)) can be used to convert a table into a vararg, which can be treated like a parameter list; note however that in Lua the list part can't have trailing nil values, not allowing you to distinguish "no value" and nil. Unpacking / destructuring to locals also helps performance since it gets rid of repeated table indexing.
function f(params)
local x, y, z, w = unpack(params)
-- use same code as if x, y, z, w were regular params
end
f{1, 2, nil}
if you use named fields, you'll have to explicitly destructure those:
function f(params)
local x, y, z, w = params.x, params.y, params.z, params.w
-- use same code as if x, y, z, w were regular params
end
f{x = 1, w = 4}
mix & match is possible:
function f(params)
local x, y, z = unpack(params)
local w = params.w
-- use same code as if x, y, z, w were regular params
end
f{1, 2, w = 4}
Metatables
The __index metatable field can be used to set a table which is indexed with name if params.name is nil, providing defaults for nil values. One major drawback of setting a metatable on a passed table is that the passed table's metatable will be lost, perhaps leading to unexpected behavior on the caller's end. You could use getmetatable and setmetatable to restore the metatable after you're done operating with the params, but that would be rather dirty, hence I would recommend against it.
Bad
function f(params)
setmetatable(params, {__index = {x = 1, y = 2, z = 3, w = 4}})
-- use params.[xyzw], possibly unpacking / destructuring
end
f{x = 1}
in addition to the presumably garbage params table, this will create (1) a garbage metatable and (2) a garbage default table every time the function is called. This is pretty bad. Since the metatable is constant, simply drag it out of the function, making it an upvalue:
Okay
local defaults_metatable = {__index = {x = 1, y = 2, z = 3, w = 4}}
function f(params)
setmetatable(params, defaults_metatable)
-- use params.[xyzw], possibly unpacking / destructuring
end
Avoiding metatables
If you want a default table without the hackyness of metatables, consider once again writing yourself a helper function to complete a table with default values:
local function complete(params, defaults)
for param, default in pairs(defaults) do
if params[param] == nil then
params[param] = default
end
end
end
this will change the params table, properly setting the defaults; use as params = complete(params, defaults). Again, remember to drag the defaults table out of the function.