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

时间:2019-05-31 02:26:14

标签: list haskell pattern-matching

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

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

2 个答案:

答案 0 :(得分:2)

“属于(头部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

答案 1 :(得分:1)

您想要

onChange = (e) => {
 const { name, value } = e.target;
 this.setState({
 [name]: value
  });
};