4 ms·
Well, the problem to optimise it is that sort will often not be the trivial bubble sort, but something like quicksort, that starts by sorting parts of the seque
by informatimago 8y ago
Well, the problem to optimise it is that sort will often not be the trivial bubble sort, but something like quicksort, that starts by sorting parts of the sequence. The fact that the first element of the result is the smallest element is therefore hidden to usual compilers. You would need a theorem prover, and even with them, it's not entirely trivial to prove.
So even for lazy programming language such as Haskell it may be impossible to transform the first sort into a selection of the extremum.
ON THE OTHER HAND!
If you used Common Lisp, and take the pain of shadowing the functions from the CL package, you could write a compiler macro on FIRST to perform this optimisation yourself.
However, this would be delicate, since in CL, the SORT function mutates the sequence, and both the predicate and the optional key function argument may have side effects. Not performing the SORT in those conditions would be a wrong optimisation.
But if your compiler-macro can determine that no side effect occurs, then you will be able to substitute the (first (sort ...)) call to a call to select the wanted extremum element.
- settings11 8y agoOP asked "this level", by the way. It is hard to write macros for every such case. However, OP may read about superoptimization, which is yet in research stage.