How can I write reverse by foldr efficiently in Haskell?

前端 未结 5 1492
误落风尘
误落风尘 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:38

    Basically, you need to transform 1:2:3:[] into (3:).(2:).(1:) and apply it to []. Thus:

    reverse' xs = foldr (\x g -> g.(x:)) id xs []
    

    The meaning of the accumulated g here is that it acts on its argument by appending the reversed partial tail of xs to it.

    For the 1:2:3:[] example, in the last step x will be 3 and g will be (2:).(1:).

提交回复
热议问题