by adwn · 9y ago · 0 comments
Ah yes, the mythical Sufficiently Smart Compiler (TM), scheduled to arrive any day now. Will it also be able to reliably transform non-trivial functions that are accidentally O(n) in memory consumption due Haskell's laziness, to O(1) versions?
The keyword here is reliably. There are many clever but brittle compiler optimizations that aren't used much in the field, because when performance is crucial, you can't rely on the compiler to detect this transformation opportunity in some cases and not in some other cases, so you code it explicitly.
What you're describing is called strictness analysis. [0] I believe that attempting to solve it in general runs up against the halting problem. That being said, GHC does perform some strictness analysis when optimization flags are turned on. [1] The language itself also includes strictness annotations on the fields of data constructors. [2] Experienced Haskell programmers know how to use these to avoid allocating unnecessary thunks.
[0] https://en.wikipedia.org/wiki/Strictness_analysis
[1] https://wiki.haskell.org/Performance/Strictness#Strictness_a...
[2] https://wiki.haskell.org/Performance/Data_types#Strict_field...
So while your O(n) code might sometimes unreliably be turned into O(1), if performance is your game you can use these kind of libraries to endure O(1).