Why can you reverse a list with the foldl?
reverse\' :: [a] -> [a]
reverse\' xs = foldl (\\acc x-> x : acc) [] xs
But this one gives me a
For a start, the type signatures don't line up:
foldl :: (o -> i -> o) -> o -> [i] -> o
foldr :: (i -> o -> o) -> o -> [i] -> o
So if you swap your argument names:
reverse' xs = foldr (\ x acc -> x : acc) [] xs
Now it compiles. It won't work, but it compiles now.
The thing is, foldl
, works from left to right (i.e., backwards), whereas foldr
works right to left (i.e., forwards). And that's kind of why foldl
lets you reverse a list; it hands you stuff in reverse order.
Having said all that, you can do
reverse' xs = foldr (\ x acc -> acc ++ [x]) [] xs
It'll be really slow, however. (Quadratic complexity rather than linear complexity.)