# Programming language compiler that will perform the composition of primitive functions with optimization

Is it possible to create a some programming language compiler that will perform the composition of primitive functions with optimization?

In fact, the maximum possible optimization in the context of function composition.
In this case, primitive means that the code consists only of while, if, break, continue statements, assignment, standard mathematical operations and functions.

Example 1. x = sqrt(x * x)x = abs(x)
Example 2. filter(filter(list, |x| % 2 == 0), |x| > 2)filter(list, |x| % 2 == 0 && |x| > 2). One list traversal instead of two.
Example 3.

for i in [0:10:1]: # from 0 to 10, step = 1
first_array[i] = i
for i in [0:10:1]: # from 0 to 10, step = 1
second_array[i] = first_array[i] + 1
for i in [0:10:2]: # from 0 to 10, step = 2
third_array[i] = first_array[i] * second_array[i] * input(i)


for i in [0:10:2]: # from 0 to 10, step = 2
third_array[i] = i * (i + 1) * input(i)


Update
The goal is to reduce the memory overhead (in fact, the array ceases to be an array and exactly the elements used in it are used for intended purpose) and time (predictable values are calculated in advance).
Output code must satisfy certain correctness criteria, e.g., must compute some particular function.

There are inputs that limit the optimization. But everything else should be optimized at compile time as much as possible.

• Is there any data type for which x = sqrt(x * x) holds true for all possible values of x? Because of potential overflow during squaring with finite data types, that would not typically be the case. Over the reals the transformation also does not hold when x is negative, as sqrt (x*x) will return a positive result. Oct 6, 2022 at 19:08
• @njuffa You're right! The programming language is supposed to be an expression language. Let's say lazy evaluation. And the optimization produces equivalent expressions (with the smallest number of operations, etc). Oct 6, 2022 at 19:40