Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haskell refer to list of list element

–This line count how many 0 are in the list

hasZero :: [Int] -> Bool
hasZero x = 0 < sum [1 | y <- x, y == 0]

–In this line I want to count how many empty list are in the list, but I got compiling erorr.

hasEmpty :: [[a]] -> Bool
hasEmpty x = 0 < [1 | y <- [x], y == []]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the first example, you summed the elements of the list your list comprehension generated. In the second, you haven’t done this. You also don’t need to put x in brackets.

hasEmpty :: Eq a => [[a]] -> Bool
hasEmpty x = 0 < sum [1 | y <- x, y == []]

This is a peculiar way to accomplish this goal. The more idiomatic way (aside from using the existing Prelude function any) would be to use pattern matching and recursion.

hasZero :: [Int] -> Bool
hasZero [] = True
hasZero (0:_) = True
hasZero (_:xs) = hasZero xs

Using any:

hasZero :: [Int] -> Bool
hasZero = any (== 0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading