Search code examples
pari-gp

Pari/GP: user defined functions


I have defined a couple of functions of arity 1, say func1(-) and func2(-). I have tested them and seen that they actually do what they are supposed to.

I wish to define a third function, say func3(-), that outputs the difference of func1(-) and func2(-). This is what I do

func3(k) = {j=func1(k)-func2(k); print(j)}

Nevertheless, it doesn't return what it ought to. Let us suppose that func1(5) outputs 10 and func2(5) outputs 2. Then, func3(5) ought to output an 8, right? It returns instead the output of func1(5) in one row, the output of func2(2) in another row, and then a zero (even though the difference of the corresponding outputs is not 0).

Do you know what's wrong with the definition of func3(-)?


Solution

  • A GP user function returns the last evaluated value. Here, it's the resut of the 'print(j)' command, which prints j (side effect) and returns 'void', which is typecast to 0 when it must be given a value, as here.

    f1(x) = 10
    f2(x) = 2
    f3(x) = f1(x) - f2(x)
    

    correctly returns 8. You didn't give the code for your func1 / func2 functions, but I expect you included a 'print' statement, maybe expecting it to return a value. That's why you get outputs on different rows, before the 0.

    If you don't like this 'return-last-evaluation-result' behaviour, you can use explicit 'return (result)' statements.