Making a Racket function that applies to lists - lisp

How to apply a function to a list in the racket?

[This answer belonged to v1 of the question which was quite different: it makes limited sense now.]
To transform a list in this way using a function f
map a function over the list which
if the element is a list, transforms it with the function f
otherwise calls f on the element.

Related

Why does Octave/Matlab use function handles

What benefit does it get from treating functions specially? For example,
function n = f(x)
2*x
endfunction
f(2) //outputs 4
f = #f
f(2) //outputs 4
If handles can be called the same way as functions, then what benefit do we get from functions being treated specially. By specially I mean that variables referring to functions can't be passed as arguments:
function n = m(f,x)
f(x)
end
m(f,2) // generates error since f is called without arguments
Why aren't functions procedures (which are always pointed to by variables) like in other functional languages?
EDIT:
It seems like my question has been completely misunderstood, so I will rephrase it. Compare the following python code
def f(x):
return 2*x
def m(f,x):
return f(x)
m(f,3)
to the octave code
function n = f(x)
2*x
end
function n = m(f,x)
f(x)
end
m(#f,2) % note that we need the #
So my question then is, what exactly is a function "object" in octave? In python, it is simply a value (functions are primitive objects which can be assigned to variables). What benefit does octave/matlab get from treating functions differently from primitive objects like all other functional languages do?
What would the following variables point to (what does the internal structure look like?)
x = 2
function n = f(x)
2*x
end
g = #f
In python, you could simply assign g=f (without needing an indirection with #). Why does octave not also work this way? What do they get from treating functions specially (and not like a primitive value)?
Variables referring to functions can be passed as arguments in matlab. Create a file called func.m with the following code
function [ sqr ] = func( x )
sqr = x.^2;
end
Create a file called 'test.m' like this
function [ output ] = test( f, x )
output = f(x);
end
Now, try the following
f=#func;
output = test(f, 3);
There's no "why is it different". It's a design decision. That's just how matlab/octave works. Which is very similar to how, say, c works.
I do not have intricate knowledge of the inner workings of either, but presumably a function simply becomes a symbol which can be accessed at runtime and used to call the instructions specified in its definition (which could be either interpreted or precompiled instructions). A "function handle" on the other hand, is more comparable to a function pointer, which, just like c, can either be used to redirect to the function it's pointing to, or passed as an argument.
This allows matlab/octave to do stuff like define a function completely in its own file, and not require that file to be run / imported for the function to be loaded into memory. It just needs to be accessible (i.e. in the path), and when matlab/octave starts a new session, it will create the appropriate table of available functions / symbols that can be used in the session. Whereas with python, when you define a function in a file, you need to 'run' / import that file for the function definition to be loaded into memory, as a series of interpreted instructions in the REPL session itself. It's just a different way of doing things, and one isn't necessarily better than the other. They're just different design / implementation decisions. Both work very well.
As for whether matlab/octave is good for functional programming / designed with functional programming in mind, I would say that it would not be my language of choice for functional programming; you can do some interesting functional programming with it, but it was not the kind of programming that it was designed for; it was primarily designed with scientific programming in mind, and it excels at that.

Apply a function in each tensor slice

Suppose we have an 3-D array (tensor) and we want to apply in each slice a function, e.g., myFun = #(x)mean(x). Is there any way to do this without for loop using build-in functions (possibly withbsxfun, or arrayfun, or accumarray)?
For loop example:
inputA = rand(10,5,20);
for sl = 1:size(A,3)
inputB = myFun(inputA(:,:,sl));
end
Thank you.
EDIT:
inputB = arrayfun(#(iterSlice) myFun(inputA(:,:,iterSlice), 1:size(inputA,3))
PS: I would like to mention, that the handler function applied is more complicated in each slice, mean was an example included in the handler function.
A for loop is already the best possibility to iterate. The only way to further improve the performance is to get rid of the iteration and have a single function call of myFun which processes all data in a vectorized way. For your example function that very simple:
myFun=#(x)permute(mean(x,1),[3,2,1])
Now it accepts 3d inputs and in the rows you find the results of the previous iterative code. You have to modify your function, there is no generic wrapper on top which can do this for you.
Regarding your edit: arrayfun is known to be slow

What does this matlab statement do

I have a statement in my MATLAB program:
f = #(A)DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus);
I understood that f is defined as the function handle to the function distancegauss which contains the parameters/arg list present inside the parentheses.
What does the variable A in #(A) do? Does it have any importance? While browsing I found that the variables within parentheses after # would be the input arguments for an anonymous function..
Can anyone explain what does that A do? Will this handle work even without that A after the # symbol ? Because it is already present as an argument to be passed after the function name.
Your code will create an anonymous function f which accepts one input A. In particular f will call the function DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus); where the value of A is whatever you input with f(A) and the other inputs must already exist in your workspace and will be passed to the function. Note: if the other variables don't exist you should get an error when calling f.
Now a reasonable question is why would you want to do this you could just call DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus); directly with whatever values you want, without having to worry about whether some of them exist.
There are two main reasons I can think of why you would do this (I'm sure there are others). Firstly for simplicity where your other inputs don't change and you don't want to have to keep retyping them or have users accidentally change them.
The other reason where you would want this is when optimizing/minimizing a function, for example with fminsearch. The matlab optimization functions will vary all inputs. If you want only vary some of them you can use this sort of syntax to reduce the number of input variables.
As to what A actually is in your case this will depend on what it does in DistanceGauss, which is not a standard MATLAB function so I suggest you look at the code for that.
"f(A)" or "f of A" or "The function of A" here has the handle "f"
DistanceGauss() here is another function that was defined elsewhere in your code.
You would set x_axis, Y_target, Y_initial, numOf, & modus before creating the function f. These arguments would stay the same for Function f, even if you try and set them again later.
'A' though, is different. You don't set it before you make the function. You can later operate on all values of A, such as if you plot the function or get the integral of the function. In that case, it would be performing the DistanceGauss function on every value of 'A', (though we can't see here what DistanceGauss function does. )
Anonymous function should be defined such as:
sqr = #(x) x.^2;
in which x shows the variable of the the function and there is no name for it (it is called anonymous!).
Although you can do something like this:
c = 10;
mygrid = #(x,y) ndgrid((-x:x/c:x),(-y:y/c:y));
[x,y] = mygrid(pi,2*pi);
in which you are modifying an existing function ndgrid to make a new anonymous function.
In your case also:
f = #(A)DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus);
This is a new anonymous function by modifying the function DistanceGauss that you may want to have a single variable A.
If you remove (A) from the code, then f would be a handle to the existing function DistanceGauss:
f = #DistanceGauss;
Now you can evaluate the function simply by using the handle:
f(A,x_axis,...)

Are there other ways to apply a function in Matlab?

If I want to use real() or abs() on some variable or vector like x, I have to write real(x) or abs(x). In Mathematica someone can use either Re[x] or Re#x. What is the equivalent of # in Matlab?
I mean using # is a shorthand notation for [] in Mathematica. Is there such a shorthand notation in Matlab?
As the other answers states; no, there is no short-hand notation similar to the ones you find in Mathematica. However, if you use the same combinations of functions often, you can create anonymous function handles that might improve the readability.
combinedfun = #(x) myfun1(myfun2(x))
or, if you want combinations of built-in functions:
absreal = #(x) abs(real(x))
In a real project I would not use anonymous functions like these, as there is not control of input arguments etc., but it might be handy if you want to do some calculations on the fly.
You can use arrayfun which needs a function to be applied on each element in x
Something like following :
arrayfun( #(y)abs(y), x )
However for simpler function simply use it on entire vector/variable/element :
abs(x)
There is no general shorthand notation for function input. But if your input arguments are strings then you can just use space to separate the function and its input arguments. So
strcat('a', 'b')
is same as
strcat a b
It cannot be used if the arguments are store in variables.

MATLAB nesting multiple input functions

Given a multiple-input MATLAB function
out=f(in1, in2)
I would like to write a second function g which generates the inputs for f, e.g.
[in1, in2]=g(in)
so that I can call something like:
out=f(g(in))
I have tried writing g as a single output function that stores in1 and in2 in a cell array so that I can feed the output of g to f using the colon operator:
in_c=g(in);
out=f(in_c{:})
but I was looking for a one-line solution, which seems not possible to achieve this way as I read in this Stack Overflow question
Is there any other way to do this?
As discussed recently, this is not possible in Matlab.
However, if you do not want to re-write your function g(x,y) to return a cell array, you can still do everything in two lines:
[in4f{1}, in4f{2}] = g(in);
out = f(in4f{:});
As an aside: Unless you're really hurting for memory, it doesn't make a lot of sense to try and force one-line statements everywhere by avoiding temporary variables. Sure, you can make your code look like CrazyPerl, but in the long run, you'll be glad for the added readability.