How can I write reverse by foldr efficiently in Haskell?

前端 未结 5 1549
误落风尘
误落风尘 2021-02-06 01:44

Note that the trivial solution

reverse a = foldr (\\b c -> c ++ [b] ) [] a

is not very efficient, because of the quadratic growth in complex

5条回答
  •  萌比男神i
    2021-02-06 02:33

    old question, I know, but is there anything non-optimal about this approach, it seems like foldr would be faster due to lazy evaluation and the code is fairly concise:

     reverse' :: [a] -> [a]
     reverse' = foldr (\x acc -> acc ++ [x]) []
    

    is (++) significantly slower than (:), which requires a few logical twists as shown in FUZxxl's answer

提交回复
热议问题