繁体   English   中英

确定Haskell列表中是否存在重复的元素

[英]Determining if there are repeated elements in a list in Haskell

我正在尝试测试重复项列表,但是当我编译并输入时

repeated [1,2,3,4] 

它输出True。 怎么了?

belongs :: Eq a => a -> [a] -> Bool
belongs n [] = False
belongs n (x:xs) | n == x = True
                 | otherwise = belongs n xs

repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = belongs (head xs) xs

你要

repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = repeated xs

“属于(头部xs)xs”检查xs的头部是否在xs内,这将始终为真。

(除非xs为空,否则您的程序将崩溃!“ head”是部分函数,​​使用空列表将崩溃)

这将解决它(也由@talex指出,但我也建议使其更通用,无需将其专门用于Integer):

repeated :: Eq a => [a] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = repeated xs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM