Home > Back-end >  How can I solve this haskell function?
How can I solve this haskell function?

Time:10-11

Specify the function that decides from a list whether it contains 0! How can I fix this ?

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

CodePudding user response:

Use pattern matching and call the function recursively while always checking the element at head for being zero and passing the rest down the recursive stack if it is not. If you find a zero, the function returns early with a True. If not, it recourses the whole list and returns False once it hits the empty list base case.

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

CodePudding user response:

The simplest solution is making use of elem :: (Foldable f, Eq a) => a -> f a -> Bool. In that case we can implement this as:

hasZero :: [Int] -> Bool
hasZero xs = 0 `elem` xs

or simpler:

hasZero :: [Int] -> Bool
hasZero = elem 0

We can also make use of any :: Foldable f => (a -> Bool) -> f a -> Bool:

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

or we can work with recursion and perform pattern matching like in @user1984's answer:

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