Luigi Sgro
Luigi Sgro

Reputation: 649

Haskell: takeWhile on list of Maybe

An infinite list of Maybe n, which, from a specific position, has only Nothing items:

someNumbers :: [Maybe Int]
someNumbers = [Just 4, Just 3, Just 2, Just 1] ++ cycle [Nothing]

I would like to count the ns statisfying a predicate p, stopping at the first Nothing:

howMany :: (Int -> Bool) -> [Maybe Int] -> Int

This is what I came up with, with explicit recursion:

howMany p ((Just n):rest)
| p n = 1 + (howMany p rest)
| otherwise = 0
howMany _ _ = 0

I am wondering if there is a better way to express this, making use of advanced Haskell abstractions.

Upvotes: 2

Views: 802

Answers (1)

Julia Path
Julia Path

Reputation: 2366

The following would work.

import Data.Maybe (isJust, maybe)
howMany p = length . filter (maybe False p) . takeWhile isJust

Or alternatively you could also use fromJust instead of maybe. Normally partial functions like fromJust are discouraged, however in this case it is safe.

import Data.Maybe (isJust, fromJust)
howMany p = length . filter (p . fromJust) . takeWhile isJust

Upvotes: 4

Related Questions