Search code examples
pari-gp

How to compute and evaluate composite function in GP?


I found a workaround to make composite function, but I believe there should be a better way to do this:

? f = x^2
%1 = x^2
? g = x^3      
%2 = x^3
? x = g
%3 = x^3
? fog = eval(f) 
%4 = x^6
? x = 2
%5 = 2
? result = eval(fog)
%6 = 64

In this method, I need to assign x many times and I don't want to use eval function. The code is not readable and maintainable.


Solution

  • PARI/GP supports the anonymous closures. So you can define the function composition on your own like this:

    comp(f: t_FUNC, g: t_FUNC) = {
        h = (x) -> f(g(x))
    };
    

    Then your code can be transformed to a more readable form:

    f(x) = x^2;
    g(x) = x^3;
    
    h = comp(f, g);
    h(x)
    ? x^6
    
    x = 2; h(x)
    ? 64
    

    Hope, this helps.