Function pointer with some but not all arguments fixed

I want to use the Brents method found in the Numerical Recepies Book to minimize the function. The signature of the minimal program looks something like this:

float brent(float (*f)(float), float *xmin, "other parameters not relevant to question")

As you can guess, brentreturns the minimum value fand stores its argument in xmin. However, the exact form of the function that I want to minimize depends on additional parameters. Let's say

float minimize_me(float x, float a, float b)

Once I have determined the values ​​of aand b, I want to minimize it with respect to x.

I could just add additional arguments to all the called functions, right up to brent, thereby changing my signature to

float brent(float (*f)(float,float,float),float a ,float b , float *xmin, ...)

and therefore call (*f)(x,a,b)inside brentevery time. However, this does not seem to me very elegant, since now I have to pass not only a pointer to minimize_me, but also two additional parameters along a whole chain of functions.

I suspect there might be a more elegant solution, such as creating a pointer to a version of the function with aand bas fixed values.

Even if this is a really obscure decision, please do not keep it from me, as I feel that it can improve my general understanding of the language.

+4
source share
3 answers

A viable way to achieve this is to use a structure to store all values ​​and pass a pointer to this function.

struct parameters{
    int valueA;
    int valueB;
};

int function(void* params){
    parameters* data = (parameters*) params;
    return data->valueA + data->valueB; // just an example
}

int main(){
    parameters myData;
    myData.valueA = 4;
    myData.valueB = 2;
    function(&myData);
    return 0;
}
+6
source

, currying, , :

f (x, y, z) a b, g , g (z) = f (a, b, z).

, C . , C . , , . . Currying/binding ISO C99 currying C? .

+5

GCC ( -std = gnu11):

float brent(float (*f)(float), float *xmin);

float minimize_me(float x, float a, float b);

int main() {
   ...
   float min_me_local(float x) { return minimize_me(x, 1, 2); }
   brent(min_me_local, xmin);
   ...
}

, , . @Nefrin, .

+1

Source: https://habr.com/ru/post/1693733/


All Articles