"Templated" functions for julia - templates

I have a function that essentially acts as a look-up table:
function lookup(a::Int64, x::Float64, y::Float64)
if a == 1
z = 2*x + y
else if a == 2
z = 5*x - 2*y
else if a == 3
...
end
return z
end
The variable a essentially determines what the relation of z is.
This function however takes a while to compile and is also not the most efficient at run time.
Could you compile the function lookup only for one instance of a (say a=1)? It is unlikely that this function will called for all possible functions of a.
I believe that such a functionality would be similar to templated functions in C++.

Julia's compiler can only dispatch on the type of arguments, not their value, as the value is only known at runtime. You can cheat a little by creating a "value type", where different values of a variable act as a different type:
lookup(::Type{Val{1}}, x, y) = 2x+y
lookup(::Type{Val{2}}, x, y) = 5x-2y
a = 2
lookup(Val{a}, 2, 3)
# 4
If you want to use this approach, you should read https://docs.julialang.org/en/stable/manual/performance-tips/#Types-with-values-as-parameters-1 first, to make sure it does not create issues with type-stability.

Related

A vector of polynomials each defined as a function

I'm trying to get a vector of polynomials, but within the vector have each polynomial defined by a function in Pari.
For example, I want to be able to output a vector of this form:
[f(x) = x-1 , f(x) = x^2 - 1, f(x) = x^3 - 1, f(x) = x^4 - 1, f(x) = x^5 - 1]
A simple vector construction of vector( 5, n, f(x) = x^n-1) doesn't work, outputting [(x)->my(i=1);x^i-1, (x)->my(i=2);x^i-1, (x)->my(i=3);x^i-1, (x)->my(i=4);x^i-1, (x)->my(i=5);x^i-1].
Is there a way of doing this quite neatly?
Update:
I have a function which takes a polynomial in two variables (say x and y), replaces one of those variables (say y) with exp(I*t), and then integrates this between t=0 and t=1, giving a single variable polynomial in x: int(T)=intnum(t=0,1,T(x,exp(I*t)))
Because of the way this is defined, I have to explicitly define a polynomial T(x,y)=..., and then calculate int(T). Simply putting in a polynomial, say int(x*y)-1, returns:
*** at top-level: int(x*y-1)
*** ^----------
*** in function int: intnum(t=0,1,T(x,exp(I*t)))
*** ^--------------
*** not a function in function call
*** Break loop: type 'break' to go back to GP prompt
I want to be able to do this for many polynomials, without having to manually type T(x,y)=... for every single one. My plan is to try and do this using the apply feature (so, putting all the polynomials in a vector - for a simple example, vector(5, n, x^n*y-1)). However, because of the way I've defined int, I would need to have each entry in the vector defined as T(x,y)=..., which is where my original question spawned from.
Defining T(x,y)=vector(5, n, x^n*y-1) doesn't seem to help with what I want to calculate. And because of how int is defined, I can't think of any other way to go about trying to tackle this.
Any ideas?
The PARI inbuilt intnum function takes as its third argument an expression rather than a function. This expression can make use of the variable t. (Several inbuilt functions behave like this - they are not real functions).
Your int function can be defined as follows:
int(p)=intnum(t=0, 1, subst(p, y, exp(I*t)))
It takes as an argument a polynomial p and then it substitutes for y when required to do so.
You can then use int(x*y) which returns (0.84147098480789650665250232163029899962 + 0.45969769413186028259906339255702339627*I)*x'.
Similarly you can use apply with a vector of polynomials. For example:
apply(int, vector(5, n, x^n*y-1))
Coming back to your original proposal - it's not technically wrong and will work. I just wouldn't recommend it over the subst method, but perhaps if you are were wanting to perform numerical integration over a class of functions that were not representable as polynomials. Let's suppose int is defined as:
int(T)=intnum(t=0,1,T(x,exp(I*t)))
You can invoke it using the syntax int((x,y) -> x*y). The arrow is the PARI syntax for creating an anonymous function. (This is the difference between an expression and a function - you cannot create your own functions that work like PARI inbuilt functions)
You may even use it with a vector of functions:
apply(int, vector(5, n, (x,y)->x^n*y-1))
I am using the syntax (x,y)->x^n*y-1 here which is preferable to the f(x,y)=x^n*y-1 you had in your question, but they are essentially the same. (the latter form also defines f as a side effect which is not wanted so it is better to use anonymous functions.

How to return void in a function in OCaml?

Simple example: I have some functions and I need to call them all, to modify a structure, only in one function. With these simple functions the task can be made in ways that don't use void, but in others tasks you have to use void. So what can you do?
type player = { mutable name : string; mutable points : int } ;;
let putname brad = match brad with
{ name = x; points = y } -> { name = brad; points = y } ;;
let putpoint guy score = match guy with
{ name = x; points = y } -> { name = x; points = score } ;;
let loosers listplayer guy = guy :: listplayer ;;
Here is the problem - How can I do the next function?
let someoneloses guy = void
guy = putpoint guy 0 ;;
listplayer = loosers (listplayer guy) ;;
Given you are using the name "void" I'm assuming you are more familiar with C (or C++). In OCaml the equivalent of "void" (the name of the type for no value) is "unit". There is another difference though: while in C the syntax is complex enough that it have constructs for no values (for instance, you can either "return a_value;" or "return;", two differents yet syntactically valid use cases for the keyword "return"), in OCaml the syntax is simpler and always require a value. So we have a notation for "nothing", which is, astutely but maybe also confusedly, is written "()".
So, the OCaml equivalent of the C:
void do_nothing(void) { return; }
is written:
let do_nothing () = ()
(notice how OCaml syntax is simpler and easier to grok once you got the "()" trick).
Now that this is hopefully clearer, back to your question.
A function that returns nothing is a function that return "()", either explicitly (as "do_nothing" above) or because it ends with an expression that has "()" as its value. For instance, an assignment (something tell me you'll love assignments), such as:
let putpoint guy score = guy.points <- score
Now back to your problem. You seem to be doing some kind of game with players represented as mutable records and some functions modifying those records as the game develop. You need not use pattern matching for that. Actually, functions such as "putpoint" above is probably what you want. But then you need some more state in your program: the list of loosers for instance is probably going to be a reference to a list that you modify etc.
This is the "imperative" side of OCaml but there is another one, which is usually regarded as more elegant although often slower in general (but not in functional languages which are optimised for this technique), consisting of refraining from altering state (changing values of things) but instead using functions merely taking values and returning values. Implemented like this, a player would be represented as an immutable record and each function acting a user would take an "old user" and return a "new user", and the same goes with the list of loosers, and so on. Actually, the whole game state would be represented as a big value that the "main loop" of your program would, given the previous value, and possible also the time and user inputs, would compute the "new state" and return it.
Have fun!
Also, your question has nothing to do with ocaml-batteries.
since you are using mutable data, you just have to assigned the value directly.
let p = {name = "me";points=0};;
let update x = x.name <- "you";
x.points <- 3;;
update p ;;

C++ Compile code for all variants of finite number of settings

For example, there is hard logic inside function void Func(long param1, long param2, long param3, long param4, long param5).
It has a lot of statements inside depends on parameters, different checks, calculations depends on combinations and etc.
And that function is called many million times and takes serious amount of execution time. And I'd like to reduce that time.
All parameters are taken from config.ini file, so, they are unknown at compile time.
But I know, that param1 may be in diapason [1..3], param2 in diapason [0..1] and etc.
So, finally, there is maybe 200 combinations of those parameters.
And I'd like my compiler compile separated 200 combination, and at the beginning of run-time, when config.ini loaded, just choose one of them, and avoid run-time calculation of parameter's dependencies.
Is that possible to achieve in C++98? Or in C++11/14?
It is certainly possible to do this using templates, since templates
can have integers instead of type parameters. For instance, the
following function
template <int iParam1, int iParam2>
int sum()
{
return iParam1 + iParam2;
}
is a function in which iParam1 and iParam2 are fixed values for
a specific template instantiation. For example, function sum<1, 2> is
a function that always returns 3.
In you case, define Func with this prototype:
template <long Param1, long Param2, long Param3, long Param4, long Param5>
void Func()
Then, create a std::map that maps a combination of parameters to a function
in which these parameters are fixed. Something like this:
using ParamCombination = std::tuple<long, long, long, long, long>;
using ParamsToFunction = std::pair < ParamCombination, std::function<void()> >;
std::map< ParamCombination, std::function<void()> > map =
{
ParamsToFunction(std::make_tuple<long, long, long, long, long>(1, 2, 2, 2, 2), Func<1, 2, 2, 2, 2>),
...
// This map will contain pairs of all possible parameter combinations
// and their corresponding functions. This is a long list but it can be
// easily generated using a script.
};
These function will have all the benefits of compile time optimizations.
Finally, during runtime, all you need to do is create a tuple that represents
a parameter combination and call the function that this tuple maps to:
auto comb = ParamCombination(1, 2, 2, 2, 2);
map[comb](); // function call
I don't know if you have considered this but you could load the config at the beginning, calculate your 200 possible solutions and put them into a lookup table. This depends on the storage you can spare. Since your number of combination seems to be small, this should be no problem. You simple merge the parameter to an integer. E.g. ( x =[0...3]; y = [0...1]) => use first 2 bit for x 3rd bit for y and so on. Calculate all possibilities using loops. And store the result inside of an array. If you don't own parameter with the power of two. You can simply multiply the possibilities. E.g x =[0...3] y =[0...5] z =[0...2] => idx = x + y*(possibilites of x = 4) + z * (pos. x = 4) * (pos. y = 6)

How to loop an argument to multiple structs with identical names?

I'm fairly new to coding and c++ and was working on a base maze game and making
it more efficient across the whole thing.
My question is basically instead of writing the same thing over and over to
define multiple structs the same way can I make something with an int on the
end that increments by 1 every loop to take position of the struct name somehow
or is this not possible?
This is my code if you are still confused by my poor explanation.
for (int g = 1; g < 30; g++)
{
if ( (x == wall(g).x && y == wall(g).y)
&& (player.x + 1 == wall1.x && player.y == wall1.y))
{
}
}
Above is the approximate idea I have come up.
I have declared many structs named (wall1, wall2, wall3, etc) at the top that
need to all run this argument.
You can use an array of struct and using index you can access to your desired struct in the runtime.
You also can try using switch-case.
That's all I have to help you.
You can inherit all your structs from a single ancestor and use a base pointer.
Alternatively, if you need to know the exact struct type, you can use RTTI.
But, of course, they cant have identical name.

Function of a letter in C++

I have the following expression:
A = cos(5x),
where x is a letter indicating a generic parameter.
In my program I have to work on A, and after some calculations I must have a result that must still be a function of x , explicitly.
In order to do that, what kind of variable should A (and I guess all the other variables that I use for my calculations) be?
Many thanks to whom will answer
I'm guessing you need precision. In which case, double is probably what you want.
You can also use float if you need to operate on a lot of floating-point numbers (think in the order of thousands or more) and analysis of the algorithm has shown that the reduced range and accuracy don't pose a problem.
If you need more range or accuracy than double, long double can also be used.
To define function A(x) = cos(5 * x)
You may do:
Regular function:
double A(double x) { return std::cos(5 * x); }
Lambda:
auto A = [](double x) { return std::cos(5 * x); };
And then just call it as any callable object.
A(4.); // cos(20.)
It sounds like you're trying to do a symbolic calculation, ie
A = magic(cos(5 x))
B = acos(A)
print B
> 5 x
If so, there isn't a simple datatype that will do this for you, unless you're programming in Mathematica.
The most general answer is "A will be an Expression in some AST representation for which you have a general algebraic solver."
However, if you really want to end up with a C++ function you can call (instead of a symbolic representation you can print as well as evaluating), you can just use function composition. In that case, A would be a
std::function<double (double )>
or something similar.