Sub functions ml - function

So I'm trying to do an assignment for an ml course, the issue is that the function requires a set type: int * int -> int for example, and the way that I see to solve the problem is to use another function (say for iteration) to solve the problem.
I believe that lisp has some kind of way of having a function be in scope for only one other function.
I think that this could be done:
fun a (x, y) =
let
fun b (i,j) = ...;
in
...;
[Not sure of exact syntax for this but I remember reading something like this only it was for temporary variables (which could be functions?]
but please correct me if this is wrong.

In ML, functions are first class citizens (i.e. values). You can bind them via let just like any other value.
Therefore, your idea is correct. It is especially a good design for functions passed as "iterators" (i.e. to map/fold/iter). Your question is too vague however for any further advise.

Related

Why would one write a C++ lambda with a name so it can be called from somewhere?

Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?
One use of this is to have a function access the enclosing scope.
In C++, we don't have nested functions as we do in some other languages.
Having a named lambda solves this problem.
An example:
#include <iostream>
int main ()
{
int x;
auto fun = [&] (int y) {
return x + y;
};
std::cin >> x;
int t;
std::cin >> t;
std::cout << fun (fun (t));
return 0;
}
Here, the function fun is basically a nested function in main, able to access its local variables.
We can format it so that it resembles a regular function, and use it more than once.
A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:
std::string key;
std::map<std::string, int> v;
one can write the following:
std::find_if( v.begin(), v.end(), [&](auto const& elem){ return elem.first == key; } );
but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:
auto matches_key = [&](auto const& elem){ return elem.first == key; };
std::find_if( v.begin(), v.end(), matches_key );
it is clearer that we do want the equality comparison and the readability is improved.
I see three things to consider when choosing between a named lamdba and a free function:
Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).
Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).
Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure
is a bit confusing in a header file (though this is debatable, of course).
requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.
When your lambda is a recursive function by itself you have no choice but to give it a name. Also, an auto keyword won't suffice and you would HAVE to declare it using an std::function with the return type and the argument list.
Below is the example for a function that returns the Nth Fibonacci number:
std::function<int(int)> fibonacci = [&](int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
You have to give it a name in order to capture it with &. And auto won't work since lambda needs its to know its types before calling itself.
This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.
But beside of that, there is no difference.
when tuning a C++ application, a named lambda is easier to tune/trace, as compared to an anonymous/unamed lambda
I always consider lamdas as a nicety - I did plenty of C++ coding without them before they were introduced. So in some ways, I don't consider that there are many shoulds or shouldn'ts surrounding them. They are there to use however they make your life easier.
One time I use named lamdas is to scope a function - i.e. the lamda is only going to be used within another function - perhaps it does something a little dangerous, that you don't want other functions to have access to or perhaps you don't want to pollute the namespace.
If your lamda is too long to be an easy one-liner, but you don't want it to be
a available outside of your scope, then a named lamda is ideal way to produce tidy easy to read code.

'Auxiliary' function in Haskell

My lecturer at the moment has a strange habit I've not seen before, I'm wondering if this is a Haskell standard or a quirk of his programming style.
Basically, he'll often do thing such as this:
functionEx :: String -> Int
functionEx s = functionExA s 0
functionExA :: String -> Int -> Int
functionExA s n = --function code
He calls these 'auxiliary' functions, and for the most part the only advantage I can see to these is to make a function callable with fewer supplied arguments. But most of these are hidden away in code anyway and in my view adding the argument to the original call is much more readable.
As I said, I'm not suggesting my view is correct, I've just not seen it done like this before and would like to know if it's common in Haskell.
Yes, this is commonplace, and not only in functional programming. It's good practice in your code to separate the interface to your code (in this case, that means the function signature: what arguments you have to pass) from the details of the implementation (the need to have a counter or similar in recursive code).
In real-world programming, one manifestation of this is having default arguments or multiple overloads of one function. Another common way of doing this is returning or taking an instance of an interface instead of a particular class that implements that interface. In Java, this might mean returning a List from a method instead of ArrayList, even when you know that the code actually uses an ArrayList (where ArrayList implements the List interface). In Haskell, typeclasses often serve the same function.
The "one argument which always should be zero at the start" pattern happens occasionally in the real world, but it's especially common in functional programming teaching, because you want to show how to write the same function in a recursive style vs. tail-recursive. The wrapper function is also important to demonstrate that both the implementations actually have the same result.
In Haskell, it's more common to use where as follows:
functionEx :: String -> Int
functionEx s = functionExA s 0 where
functionExA s n = --function code
This way, even the existence of the "real" function is hidden from the external interface. There's no reason to expose the fact that this function is (say) tail-recursive with a count argument.
If the special case definition is used frequently, it can be an advantage to do this. For example, the sum function is just a special case of the fold function. So why don't we just use foldr (+) 0 [1, 2, 3] each time instead of sum [1,2,3]? Because sum is much more readable.

Variable Availability in Erlang

I am wondering if it is possible to have a function get a variable if it is not passed explicitly.
The issue is mainly about cleaning up my code, as I have many functions that need to pass every variable that will ever be used to the next function.
In SML for example, one could easily accomplish this with something like:
fun myFun varx vary varz
let
fun otherFun () = varx
fun otherFun2 () = vary
in
otherFun() + otherFun()
end
Is there a way to allow other functions to see variables that are not explicitly passed to it? Or is this just not the way one would program in erlang?
Erlang variable scope works much in the same way:
E.g:
add_two(X) ->
F = fun(Y) ->
X + Y
end,
F(2).
Hope this helps.

Is it possible to learn the functions using just header files?

In case of lack of proper updated tutorials for some particular library functions (in my case, latest allegro5), how can one learn by oneself how to call and use those functions? Is there some clue in header files?
thanks in advance
The header files are going to provide you with the bare minimum information required to correctly compile a program with those functions. It has the types, constants, and function prototypes. Nothing (short of comments) is going to explain how to correctly use the functions, just how to call them.
General
For example, if you see:
int do_something(int n, const char* desc);
You can only infer that you need to pass an integer n and a (C) string desc. That function returns an integer as well.
For a more complex example:
typedef struct {
int foo;
double bar;
} blam_t;
void munge(blam_t info);
You know that munge takes one argument of type blam_t which is a custom structure, as defined above. You could use that to create a blam_t variable and pass it to munge():
blam_t myvar;
myvar.foo = 42;
myvar.bar = 0.67;
munge(myar);
Allegro5
If we look at the source of include/allegro5/display.h we see things like this:
AL_FUNC(void, al_set_new_display_flags, (int flags));
This is an uncommon way of defining functions. They are using a macro AL_FUNC to define their functions. We see (by clicking on it) that AL_FUNC is defined as:
#define AL_FUNC(type, name, args) type name args
So that first example basically becomes:
void al_set_new_display_flags(int flags);
And we can call it with just an integer argument.
Without any documentation, you can only hope to learn by trying the functions. Then this becomes more a reverse engineering task.

Is there a function head in mathematica that can be used to define an input type?

I am defining a function that takes as input a function and I want to specify it in the input type i.e. Operat[_?FunctionQ]:=...
But there is no functionQ as of yet in mathematica. How do I get aroud this except not specifying any type at all.
Any ideas?
Oh!
This: Test if an expression is a Function?
may be the answer i am looking for. I am reading further
Is the solution proposed there robust?, i.e.:
FunctionQ[_Function | _InterpolatingFunction | _CompiledFunction] = True;
FunctionQ[f_Symbol] := Or[
DownValues[f] =!= {},
MemberQ[ Attributes[f], NumericFunction ]]
FunctionQ[_] = False;
The exhibited definition has great utility. The question is: what exactly constitutes a function in Mathematica? Pure functions and the like are easily to classify as functions, but what about definitions that involve pattern-matching? Consider:
h[g[x_]] ^:= x + 1
Is h to be considered a function? If so, it will be hard to identify as it will entail examining the up-values of every symbol in the system to make that determination. Is g a function? It has an up-value, but g[x] is an inert expression.
What about head composition:
f[x_][y_][z_] := x + y + z
Is f a function? How about f[1] or f[1][2]?
And then there are the various capabilities like JLink and NETLink:
Needs["JLink`"]
obj = JavaNew["java.util.Date"]
obj#toString[]
Is obj#toString a function?
I hate to bring up these problems without offering solutions -- but I want to emphasize that the question as to what constitutes a function in the Mathematica context is a tricky one. It is tricky from both the theoretical and practical standpoints.
I think that the answer to whether the exhibited function test is complete really depends upon the types of expressions that you will be feeding it in your specific application.