在Haskell中获取列表的最后一个元素的最快方法 [英] Fastest way to get the last element of a list in Haskell

查看:353
本文介绍了在Haskell中获取列表的最后一个元素的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取Haskell中列表的最后一个元素的最快方法是什么?在下一次迭代中,我想删除列表的第一个和最后一个元素。什么是最优雅的方式来做到这一点?我试图列表理解,但看起来效率不高! $ c>和 init 可以很好地完成一次性工作。然而,它们都是 O(n),所以如果您需要经常处理列表的两端,就像您似乎暗示的那样,您可能需要考虑使用 Data.Sequence 代替,它支持 O(1)插入和移除两端的商品。


What is the fastest way to get the last element of a list in Haskell. Also in next iteration, I want to remove first and last element of the list. What is the most elegant way to do it? I am trying list comprehension, but that does not look very efficient!

解决方案

last and init will do the job just fine for a one-off. However they are both O(n), so if you need to manipulate both ends of a list often, as you seem to imply, you might want to consider using Data.Sequence instead, which supports O(1) insertion and removal of items at both ends.

这篇关于在Haskell中获取列表的最后一个元素的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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