简体   繁体   中英

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:

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.

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. Then you just check that they are all elem ents of the original list.

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 . 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).

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?

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 :

  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_ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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