Implement some :: [Bool] -> Bool function that decides conditions a list of whether it has a true element. In this task, the or function its use is not permitted.
- Test:
- some [succ 'a' / = 'b', 1 1 / = 2, 10 <20] == True
- some [succ 'a' / = 'b', 1 1 / = 2, 10> = 20] == False
- some [] == False
some :: [Bool] -> Bool
some [] = False
some (False: _) = False
some (_: False) = False
some _ = True
How can I fix my code ? I do not know what is the problem.
CodePudding user response:
some :: [Bool] -> Bool
some [] = False
some (False:xs) = some xs
some (True:_) = True
The problem with your current code is that you don't recurse further if you see the first element is False
. When you see a False
you have to continue checking the rest of the list up until either the list is exhausted or you find a True
. Whenever you find a True
you can bail out early and just return a True
because you don't care about the rest.
CodePudding user response:
In the pattern (x:xs)
, x
is the first item of the list, and xs
is a list of the remaining elements. Such list can not be False
. It is possible a list full of False
values, but not a Bool
.
You some
thus looks like:
some :: [Bool] -> Bool
some [] = False
some (x:xs) = x || some xs