Home > Mobile >  Haskell refer to list of list element
Haskell refer to list of list element

Time:10-09

--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 == []]

CodePudding user response:

There are 2 issues in your second method - you are missing sum which does the count in the first one, and you are wrapping passed list into another one, it should be y <- x as in the first one:

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

Which can be rewritten as:

hasEmpty :: [[a]] -> Bool
hasEmpty = any null

CodePudding user response:

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)
  • Related