如何在Haskell中有效地通过foldr写回? [英] How can I write reverse by foldr efficiently in Haskell?

查看:119
本文介绍了如何在Haskell中有效地通过foldr写回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,简单的解决方案

Note that the trivial solution

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

并不是非常有效率,因为复杂性的平方增长。如果试图使用通常的foldl来进行foldr转换(盲目地),但是我的尝试

is not very efficient, because of the quadratic growth in complexity. If have tried to use the usual foldl to foldr conversion (blindly), but my attempt

foldr (\b g x -> g ((\x old -> x:old) x b)) id list []

没有按我的预期工作。

推荐答案

试试这个:

Try this:

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

虽然通常使用 foldl'

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

这篇关于如何在Haskell中有效地通过foldr写回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆