【问题标题】:Determining if there are repeated elements in a list in Haskell确定 Haskell 列表中是否存在重复元素
【发布时间】:2019-05-31 02:26:14
【问题描述】:

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

repeated [1,2,3,4] 

它输出真。怎么了?

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

【问题讨论】:

  • belongs (head xs) xs 检查xs 的第一个元素(假设它存在)是否属于xs。你想要repeated xs
  • repeated 给出的答案与预期不同的最小列表是什么?现在您已经确定了一个最小的列表,您可以开始在 ghci 中评估您定义的子表达式,以查看它们中的哪些行为与您的预期不同。最终,您将深入到一个非常小的表达式,以至于 1. 为什么您的期望是错误的或 2. 为什么您编写的代码是错误的。这是调试的精髓,你应该预料到你编写代码的大部分时间和精力都会花在这个过程上。

标签: list haskell pattern-matching


【解决方案1】:

你想要的

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

【讨论】:

    【解决方案2】:

    "belongs (head xs) xs" 检查xs的头部是否在xs之内,永远为真。

    (除非xs为空,否则你的程序会崩溃!“head”是一个偏函数,空列表会崩溃)

    这将解决它(正如@talex 所指出的那样,但我也建议让它更通用,无需将其专门化为整数):

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-10
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 2015-07-17
      相关资源
      最近更新 更多