Can 'all' be applied to a list of Maybe?
haskell
Solution
> all (<= Just 9) [Just 3, Just 6, Nothing, Nothing, Just 7]
True
This works because `Nothing` is less than any `Just x`.
Alternatively, one can use `catMaybes :: [Maybe a] -> [a]` from the `Data.Maybe` module to discard the `Nothing`s, and remove the `Just` wrappers, turning the list into a list of numbers, which can then be handled as usual:
> all (<= 9) $ catMaybes [Just 3, Just 6, Nothing, Nothing, Just 7]
True
Another alternative: define your own predicate on `Maybe Int`.
let p :: Maybe Int -> Bool
p Nothing = True
p (Just x) = x <= 9
in all p [Just 3, Just 6, Nothing, Nothing, Just 7]
Even better: define `p` using `maybe`, as Zeta suggests.
Yet another alternative, using a list comprehension and `and`:
and [ x <= 9 | Just x <- [Just 3, Just 6, Nothing, Nothing, Just 7] ]
Problem
Is it possible to use `all` on a `[Maybe Int]` list? I know `all (< 9) [2,4,6,8,10]` returns `False`, but that is using a list with just integers. I am trying to accomplish something similar except with a list that looks like this: `[Just 3, Just 6, Nothing, Nothing, Just 7]` I want `all (<=9) [Just 3, Just 6, Nothing, Nothing, Just 7]` to return `True`