在列表中查找第一个重复元素

在列表中查找第一个重复元素

本文介绍了在列表中查找第一个重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Haskell我很新。我正在尝试在Haskell中编写代码,该代码从列表中找到第一个重复元素,并且如果它没有重复的元素,则消息不会重复。我知道我可以通过 nub 函数来做到这一点,但我试图在没有它的情况下做到这一点。

解决方案

 将限定数据集合导入为集合

dup :: Ord a => [a] - >可能是
dup xs = dup'xs Set.empty
其中dup'[] _ = Nothing
dup'(x:xs)s = Set.member xs
then只需x
else dup'xs(Set.insert xs)

dupString ::(Ord a,Show a)=> [a] - > [Char]
dupString x = case $ x
只要x - > First duplicate:++(show x)
Nothing - > 不重复

main :: IO()
main = do
putStrLn $ dupString [1,2,3,4,5]
putStrLn $ dupString [1,2,1,2,3]
putStrLn $ dupStringHELLO WORLD

这是它是如何工作的:

  * Main>主要
不重复
第一个重复:1
第一个重复:'L'


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.

解决方案

This is one way to do it:

import qualified Data.Set as Set

dup :: Ord a => [a] -> Maybe a
dup xs = dup' xs Set.empty
  where dup' [] _ = Nothing
        dup' (x:xs) s = if Set.member x s
                           then Just x
                           else dup' xs (Set.insert x s)

dupString :: (Ord a, Show a) => [a] -> [Char]
dupString x = case dup x of
                  Just x  -> "First duplicate: " ++ (show x)
                  Nothing -> "No duplicates"

main :: IO ()
main = do
       putStrLn $ dupString [1,2,3,4,5]
       putStrLn $ dupString [1,2,1,2,3]
       putStrLn $ dupString "HELLO WORLD"

Here is how it works:

*Main> main
No duplicates
First duplicate: 1
First duplicate: 'L'

这篇关于在列表中查找第一个重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:59