Write a function that reduces compositions of linear operators
GolfScript, 41 40 23 19 characters
{2,0+%/-{@*+}++}:k;
Thanks to Peter Taylor for pointing out this solution. Accepts two function bodies as arguments.
The following examples show how to use function k
:
# As function
{2*3+} {3*4+} k # => {11 6 @*+}
# Apply to value
5 {2*3+} {3*4+} k ~ # => 41
If one wants to retain the original output format, the following 22 character solution is possible:
{2,0+%/-{*}+\+{+}+}:k;
{2*3+} {3*4+} k # => {6 * 11 +}
Explanation of the code:
{ # on stack are functions g h
2, # build array [0 1] -> g h [0 1]
0+ # append 0 -> g h [0 1 0]
% # apply function h to each element -> g [h(0) h(1) h(0)]
/ # apply function g to each element
# and break up the array -> g(h(0)) g(h(1)) g(h(0))
- # subtract last two -> g(h(0)) g(h(1))-g(h(0))
{@*+}++ # append function body to these values
}:k; # save function to variable k
Mathematica 15
Define g, h as pure functions
g
and h
are defined as pure functions (awaiting a value or independent variable to be assigned)
g = 2 # + 3 &;
h = 3 # + 4 &;
g[x]
h[x]
3 + 2 x
4 + 3 x
Method #1: Compose g
of h
directly (15 chars)
g@h@x//Simplify
11 + 6 x
Or, alternatively: (17 chars)
g[h[x]]//Simplify
Method #2: Define f
(25 chars= 13 + 10 chars for Simplify)
f=Composition
f[g, h][x]
f[g, h][x] // Simplify
Composition[g, h][x]//Simplify
f[g, h][1]
Table[f[g, h][x], {x, 1, 13}]
3 + 2 (4 + 3 x)
11 + 6 x
11 + 6 x
17
{17, 23, 29, 35, 41, 47, 53, 59, 65, 71, 77, 83, 89}
Haskell, 31
(f%g)x=f(g 0)+x*(f(g 1)-f(g 0))
Version in which the function body contains only variables (equivalent at run time, but closer to the question's form), 38 characters:
(f%g)x=a*x+b where h=f.g;b=h 0;a=h 1-b
Note that in both cases, since Haskell uses curried functions, there is no explicit construction of the composed function as it is implicit in %
being defined with three arguments: function f, function g, value x.
Example use:
> ((\x -> 2*x + 3)%(\x -> 3*x + 4)) 0
11
> ((\x -> 2*x + 3)%(\x -> 3*x + 4)) 4
35
Ungolfed second form:
(f % g) x = a * x + b -- equivalent: (f % g) = \x -> a * x + b
where
h = f . g -- use built in function composition to bootstrap
b = h 0 -- constant term of composed function
a = h 1 - h 0 -- linear term of composed function