【发布时间】: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