This is the function of the GHC compiler. Basically, GHC can recognize when a list is used in a pipeline, and can convert the entire construct to the while
-loop equivalent in C, which does not highlight the list at all.
The reason this works with foldr
rather than foldl
depends on the function g
that you use in your example. Since foldr
, unlike foldl
, accumulates the results of the function specified as a parameter (aka: foldl
requires the entire list before it can actually evaluate the function g
, so in this case it creates a huge βcrashβ of unvalued functions and the final element in the list so in this case it uses a lot more memory - while foldr
can start evaluating g
as soon as it gets any input to the list), it is called "strict" in its accumulator, and some assumptions can be made by the compiler, which can weight gain ty to optimization.
If, for example, the function g
gives a value that is a list, it can continue the aforementioned pipeline optimization strategy, basically considering foldr
as a map
and doing the whole construction (from to generate a list to list consumption) in a strict loop. This is only possible because foldr
gives exactly one list item for each list item that it consumes, that foldl
not guaranteed (especially for infinite lists).
dflemstr
source share