查找列表中的第一个重复元素
我对 Haskell 很陌生。我正在尝试在 Haskell 中编写代码来查找列表中的第一个重复元素,如果它没有重复元素,则不会给出重复的消息。我知道我可以通过 nub
函数来做到这一点,但我试图在没有它的情况下做到这一点。
I am very new to Haskell. I am trying to write code in Haskell that finds the first duplicate element from the list, and if it does not have the duplicate elements gives the message no duplicates. I know i can do it through nub
function but i am trying to do it without it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种方法:
它的工作原理如下:
This is one way to do it:
Here is how it works:
这不是您的最终答案,因为当一个元素被重复多次而不是立即返回时,它会做不必要的工作,但它说明了您如何系统地运行所有可能性(即“列表中的这个元素是否有在列表的下方重复吗?”)
This is not the your final answer, because it does unnecessary work when an element is duplicated multiple times instead of returning right away, but it illustrates how you might go about systematically running through all the possibilities (i.e. "does this element of the list have duplicates further down the list?")
如果您仍在研究 Haskell,我想您可能会喜欢一个更快但更复杂的解决方案。它的运行时间为 O(n) (我认为),但对列表的类型有稍微严格的限制,即必须是
Ix
类型。AccumArray 是一个非常有用的函数,如果您还没有的话,强烈建议您研究一下。
不过请注意,
(最小 xs,最大 xs)
大小的数组可能会真正增加您的空间需求。In case you are still looking into Haskell I thought you might like a faster, but more complicated, solution. This runs in O(n) (I think), but has a slightly harsher restriction on the type of your list, namely has to be of type
Ix
.accumArray
is an incredibly useful function, really recommend looking into it if you haven't already.Watch out tho, an array of size
(minimum xs,maximum xs)
could really blow up your space requirements.