我找到了一种解决方法来制作复合功能,但我相信应该有更好的方法来做到这一点:
? 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
在这种方法中,我需要x
多次分配,我不想使用eval
函数。代码不可读和不可维护。
我找到了一种解决方法来制作复合功能,但我相信应该有更好的方法来做到这一点:
? 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
在这种方法中,我需要x
多次分配,我不想使用eval
函数。代码不可读和不可维护。
You can simplify Piotr's nice answer to
comp(f, g) = x->f(g(x));
Indeed, you do not need to assign to the (global) variable h
in the comp
function itself. Also, the braces are not necessary for a single-line statement, and neither are type annotations (which are meant to optimize the byte compiler output or help gp2c
; in this specific case they do not help).
Finally the parentheses around the argument list are optional in the closure definition when there is a single argument, as (x)
here.
I would modify the examples as follows
f(x) = x^2;
g(x) = x^3;
h = comp(f, g);
? h('x) \\ note the backquote
%1 = x^6
? h(2)
%2 = 64
The backquote in 'x
makes sure we use the formal variable x
and not whatever value was assigned to the GP variable with that name. For the second example, there is no need to assign the value 2
to x
, we can call h(2)
directly
P.S. The confusion between formal variables and GP variables is unfortunate but very common for short names such as x
or y
. The quote operator was introduced to avoid having to kill
variables. In more complicated functions, it can be cumbersome to systematically type 'x
instead of x
. The idiomatic construct to avoid this is my(x = 'x)
. This makes sure that the x
GP variable really refers to the formal variable in the current scope.
PARI/GP 支持匿名闭包。所以你可以像这样自己定义函数组合:
comp(f: t_FUNC, g: t_FUNC) = {
h = (x) -> f(g(x))
};
然后您的代码可以转换为更易读的形式:
f(x) = x^2;
g(x) = x^3;
h = comp(f, g);
h(x)
? x^6
x = 2; h(x)
? 64
希望这可以帮助。