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

前端 未结 6 1800
栀梦
栀梦 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:35

    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.)

提交回复
热议问题