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.