Search code examples
optimizationprogramming-languagesprogram-transformation

Can any language "deeply" combine or simplify functions?


It is common to have two or more functions/methods combined and work as a whole. For examples:

To "combine" functions in javascript in a functional way?

Is it possible in C++11 to combine functions into a new function?

However, I was wondering if something like this can be done:

Function<Integer, Integer> f = x -> x + 1;
Function<Integer, Integer> g = x -> x * 2;
Function<Integer, Integer> h = f.compose(g);
** **
h.toString  //get x-> x*2+1 , what I want

The functions are "deeply" combined, which is similar to the simplification of expressions in mathematical software like Matlab.

I know there are some useful techniques in compilaters and I am seeking how it can be done in high-level languages.

By the way, I guess it is theoretically possible using JVM bytecode manipulation but that would be too complex.


Solution

  • Note that languages usually do not specify the (possible) optimizations to be applied. Optimizations are delegated to compilers and runtime systems.

    Functional languages, such as Haskell, provide many function-based composition features enabling the targetted optimizations. You can look at function composition, lazy evaluation, partial application and higher order functions.

    Please note that a lot of work has been done regarding the specific case of sequence-based computations. See generators in Python or the more general/abstract concept called ranges. Ranges are available for example in the D and C++20 programming languages. The composition and the optimization of ranges are achieved at a rather low level and compilers are generally not responsible for their specific optimizations.

    Finally, several compilers are able to perform rather clever high-level transformations (see polyhedral model for loops, inter-procedural optimization for functions).