Function whose output is function in Julia - function

I am Julia user.
I want to define a function whose output is a function.
This is an example.
function get_f(p::Int)
if p == 1
return f(x) = x^2
else
return f(x) = cos(x)
return f
end
But it does not work!
f(x) = get_f(2)
f(2)
# UndefVarError x not defined.
Also, when I run the code, we have the following WARNING.
WARNING: Method definition f(Int64) in module Main at REPL[88]:4
What is the problem? If you know another good way, please tell me.
I guess we can write more sophisticated code using 'struct', but I don't know how.

We should use anonymous functions.
function get_f(p::Int)
if p == 1
return (x,y) -> x+y
elseif p == 2
return (x,y) -> norm(x-y)
else
return (x,y) -> x*y
end
end
f = get_f(2)
f(3,2) # 1.0
It works!

Related

OCaml meaning of "in"

Lets assume the following function
val foo : int -> int -> bool -> int
let foo x y b =
let x,y = if x > y then y,x else x,y in
let rec loop x y b =
if x >= then x
else if b then loop (x+1) y (not b)
else loop x (y-1) (not b)
in
loop x y b
I still don't quite understand the concept of the "in".
Does the line mean "let x,y = ... in" that it is executed immediately or only when you "Call" it? And when i dont need to call it why do i need the last line loop x y b?
Thanks in advance :)
in is just part of the OCaml syntax - let PATTERN = EXPR1 in EXPR2 is an expression which binds the result of EXPR1 to PATTERN and then evaluates EXPR2 with the new bindings present. In some languages like F# and Haskell, you don't (always) need in - it's inferred from the indentation. OCaml syntax is indentation insensitive which requires it to have an explicit in.
Does the line mean "let x,y = ... in" that it is executed immediately or only when you "Call" it?
It's evaluated immediately.
And when i dont need to call it why do i need the last line loop x y b?
In this code, the previous line defines a function named loop with 3 arguments, and then later you call the function with the arguments x y b.

Uppercase in name of a function in Julia

I am fairly new to Julia and got confused with the following code. After a function LucasTree is defined, it is used again as lt. Does Julia have some kind of role where I can recall a function using the uppercase abbreviation? If so, where can I find a nice reference for this feature?
function LucasTree(;γ = 2.0,
β = 0.95,
α = 0.9,
σ = 0.1,
grid_size = 100)
ϕ = LogNormal(0.0, σ)
shocks = rand(ϕ, 500)
# build a grid with mass around stationary distribution
ssd = σ / sqrt(1 - α^2)
grid_min, grid_max = exp(-4ssd), exp(4ssd)
grid = range(grid_min, grid_max, length = grid_size)
# set h(y) = β * int u'(G(y,z)) G(y,z) ϕ(dz)
h = similar(grid)
for (i, y) in enumerate(grid)
h[i] = β * mean((y^α .* shocks).^(1 - γ))
end
return (γ = γ, β = β, α = α, σ = σ, ϕ = ϕ, grid = grid, shocks = shocks, h = h)
end
function lucas_operator(lt, f)
# unpack input
#unpack grid, α, β, h = lt
z = lt.shocks
Af = LinearInterpolation(grid, f, extrapolation_bc=Line())
Tf = [ h[i] + β * mean(Af.(grid[i]^α .* z)) for i in 1:length(grid) ]
return Tf
end
No, this does not exist. It would be too nonunique to be practical, and moreover function names in Julia by convention should be entirely lowercase (structs/types can be CamelCase, but not functions, with the possible exception of constructors*).
In any case, all that is happening here in the code you have posted is that the function lucas_operator takes two arguments, lt and f, which can then be used within that lucas_operator function. These could in principle be anything, and regardless of what they are named outside the scope of the function, they will be named lt and f within the scope of the function. So for example:
function example(foo, bar)
return foo(2*bar)
end
if you then call
example(somereallylongfunctionname, somevariable)
then that will return the equivalent of
somereallylongfunctionname(2*somevariable)
or similarly
example(SomeImproperlyCapitalizedFunction, somevariable)
# equivalent to SomeImproperlyCapitalizedFunction(2*somevariable)
in either case, regardless of its name outside the scope of the example function, the first argument passed to the function will be known as foo within the function.
* Aside about constructors: that would be a function that is used to construct a custom type. This doesn't quite do that, but it does return an instance of a NamedTuple which then seems to be treated somewhat like a type/struct in the subsequent code, so perhaps it could be counted as a constructor.

Is it possible to know the name of the variable that provides the value in a function call in Octave?

Say that myFunction has been invoked from somewhere like this
...
myFunction (b);
...
Now, in the definition of myFunction, can I obtain the name of the variable in the call?
function myFunction (a)
...
inputVble = whoscalling; % this will result in "b"
...
May be it can be done if b is a global variable?
Note: this is not like in a couple other questions, where you want to know the name of the input argument, i.e. a.
function ret = doit (a, b)
inputname (1)
inputname (2)
ret = a + b;
endfunction
x = 4;
y = 5;
doit (x, y)
returns
ans = x
ans = y
ans = 9
But I want to mention that in my opinion, making a function somewhat dependent on the function names is bad style and shouldn't be done even if it's possible.
EDIT: I think the main reasonable use for inputname is inside a display routine for #classes. For example http://hg.savannah.gnu.org/hgweb/octave/file/51a1d1164449/examples/code/%40polynomial/display.m
function display (p)
...
fprintf ("%s =", inputname (1));
Or inside celldisp:
octave:2> a = {"huhu", pi}
a =
{
[1,1] = huhu
[1,2] = 3.1416
}
octave:3> celldisp (a)
a{1} =
huhu
a{2} =
3.1416

Pointer to MATLAB function?

So I have a for-loop in MATLAB, where either a vector x will be put through one function, say, cos(x).^2, or a different choice, say, sin(x).^2 + 9.*x. The user will select which of those functions he wants to use before the for-loop.
My question is, I dont want the loop to check what the user selected on every iteration. Is there a way to use a pointer to a function, (user defined, or otherwise), that every iteration will use automatically?
This is inside a script by the way, not a function.
Thanks
You can use function_handles. For your example (to run on all available functions using a loop):
x = 1:10; % list of input values
functionList = {#(x) cos(x).^2, #(x) sin(x).^2 + 9*x}; % function handle cell-array
for i=1:length(functionList)
functionOut{i} = functionList{i}(x); % output of each function to x
end
You can try something like the following:
userChoice = 2;
switch userChoice
case 1
myFun = #(x) sin(x).^2 + 9.*x;
case 2
myFun = #(x) cos(x).^2;
end
for k = 1:10
x(k,:) = myFun(rand(1,10));
end

How do I return a function as an output value in MATLAB?

I am writing a function makeFunction(data). I want it to return a function, not a matrix, vector, or scalar. How do I do this?
Use function handles.
function f = functionReturner(u)
% creates the function x.^u to return as an example
f = #(x) x.^u;
If I save this function, then call functionReturner, the argument is itself a function.
f = functionReturner(3);
f(2.5)
ans =
15.625
You can easily enough verify that 15.625 is indeed 2.5^3.