Why can you reverse list with foldl, but not with foldr in Haskell

前端 未结 6 1816
栀梦
栀梦 2021-02-04 09:49

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

6条回答
  •  余生分开走
    2021-02-04 10:13

    You can use foldr to reverse a list efficiently (well, most of the time in GHC 7.9—it relies on some compiler optimizations), but it's a little weird:

    reverse xs = foldr (\x k -> \acc -> k (x:acc)) id xs []
    

    I wrote an explanation of how this works on the Haskell Wiki.

提交回复
热议问题