简体   繁体   English

Haskell检查Int的列表是否完整

[英]Haskell Check if a list of Int's is complete

Not easy way to explain this, but I will try. 解释这个并不容易,但我会尝试。 I think i'm confusing my method with some C, but here it goes: 我想我的方法与一些C混淆了,但在这里:

I want to check if a list is complete, like this: 我想检查列表是否完整,如下所示:

main> check 1 [1,3,4,5]
False

main> check 1 [1,2,3,4]
True

It's a finite list, and the list doesn't have to be ordered. 这是一个有限的列表,列表不必订购。 But inside the list there most be the number that misses to be True. 但在列表中,大多数都是错过的数字。 In the first case it's the number 2. 在第一种情况下,它是数字2。

This is my version, but it doesn't even compile. 这是我的版本,但它甚至没有编译。

check :: Eq a => a -> [a] -> Bool
check n [] = False
check n x | n/=(maximum x) = elem n x && check (n+1) x
          | otherwise = False

So if I understand this correctly, you want to check to see that all the elements in a list form a sequence without gaps when sorted. 因此,如果我理解正确,您需要检查列表中的所有元素是否在排序时形成没有间隙的序列。 Here's one way: 这是一种方式:

noGaps :: (Enum a, Ord a) => [a] -> Bool
noGaps xs = all (`elem` xs) [minimum xs .. maximum xs]

[minimum xs .. maximum xs] creates a sequential list of all values from the lowest to the highest value. [minimum xs .. maximum xs]创建从最低值到最高值的所有值的顺序列表。 Then you just check that they are all elem ents of the original list. 然后你只需检查它们是原始列表的all elem

Your function doesn't compile because your type constraints are greater than what you declare them as. 您的函数无法编译,因为您的类型约束大于您声明的类型约束。 You say that a only needs to be an instance of Eq - but then you add something to it, which requires it to be an instance of Num . 你说, a仅需要实例Eq -但你添加的东西给它,这要求它的一个实例Num The way you use the function also doesn't make sense with the signature you declared - check [1,2,3,4] is a Bool in your example, but in the code you gave it would be Eq a => [[a]] -> Bool (if it compiled in the first place). 您使用该函数的方式对于您声明的签名也没有意义 - 在您的示例中, check [1,2,3,4]Bool ,但在您给出的代码中,它将是Eq a => [[a]] -> Bool (如果它首先编译)。

Do you only need this to work with integers? 你只需要这个就可以用整数吗? If not, give some example as to what "complete" means in that case. 如果没有,举一个例子说明在这种情况下“完整”是什么意思。 If yes, then do they always start with 1? 如果是,那么他们总是以1开头吗?

Here's another take on the problem, which uses a function that works on sorted lists, and use it with a sorted input. 这是对问题的另一种看法,它使用一个适用于排序列表的函数,并将其与排序输入一起使用。

The following will check that the provided list of n Int contains all values from 1 to n : 以下将检查提供的n Int列表是否包含从1n所有值:

  check :: (Num a, Ord a) => [a] -> Bool

  import List

  check l = check_ 1 (sort l)
     where check_ n [] = True
                 check_ n [x] = n == x
                 check_ n (x:y:xs) = (x+1)==y && check_ (n+1) (y:xs)

Note the use of List.sort to prepare the list for the real check implemented in check_ . 注意用List.sort准备列表中实现真正的检查check_

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

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