How can I write reverse by foldr efficiently in Haskell?

前端 未结 5 1496
误落风尘
误落风尘 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条回答
  •  青春惊慌失措
    2021-02-06 02:40

    Try this:

    reverse bs = foldr (\b g x -> g (b : x)) id bs []
    

    Though it's usually really better to write it using foldl':

    reverse = foldl' (flip (:)) []
    

提交回复
热议问题