Does some basic list operation in Haskell(e.g. ghc) are optimized equivalently to their imperative counterparts?
For example if I have some finite but computed in runtime list does its length is attached to this list or evaluating function (length xs) have to traverse whole list recursively?
Is there some list of common Haskell(ghci or in general) optimization made by compiler?
Haskell is very good at doing optimizations on lists, but not the type you describe. Haskell doesn’t have “special” handling for lists — they’re like other normal Haskell types, albeit with some built-in syntactic sugar. It’s nothing more special than
would be.
Haskell optimizes lists using what’s called foldr/build fusion, which e.g. optimizes
map f (filter p list)so that it doesn’t produce an intermediate list for thefilter, but does both the map and the filter in the same traversal. See here for details on what “fuses,” or read here for more details on how it works.Additionally, Haskell’s more modern array libraries use a more aggressive type of fusion that can e.g. fuse
sum (map f (enumFromN 0 n))to a tail-recursive iteration from0ton-1, which is basically exactly what you want. Investigate the vector package, this blog post for what stream fusion can do, and this paper for details.