I am learning about reversing lists.
I know how to do it super slow with recursion and (++), and I know how to do it reasonably fast with recursion and an accumulator.
Now I am looking into doing it with a fold...
function. A simple
rev1r :: [a] -> [a]
rev1r lst = foldr (\x l -> x:l) [] lst
does not do the trick, because it builds up the new list the same way it āateā the source list. But foldl
seem to be exactly what I need here!:
rev1l :: [a] -> [a]
rev1l lst = foldl (\l x -> x:l) [] lst
I have read everywhere that foldl
is super slow because it stacks all intermediate terms up before it resolves them. (Note: I am not allowed to use foldl'
because it is not in the Prelude.) So I test my rev1l
with something big:(*)
rev1l (3:(take 1000000 [1,1..]))) !! 1000000
However, this seems to run as fast as the standard reverse
.
So my question is: How can foldl
be so fast? Do I overlook something?
(*) I use the added 3
which I print out to make sure GHC canāt opimise things out.