Skip to content

Commit

Permalink
IntegerInterval: add memberCount
Browse files Browse the repository at this point in the history
Returns the number of integers that lie within an integer interval.
  • Loading branch information
ncfavier authored and Bodigrim committed Dec 21, 2023
1 parent 21d7a82 commit 5155346
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Data/IntegerInterval.hs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ module Data.IntegerInterval
, lowerBound'
, upperBound'
, width
, memberCount

-- * Universal comparison operators
, (<!), (<=!), (==!), (>=!), (>!), (/=!)
Expand Down Expand Up @@ -309,6 +310,17 @@ width x
(Finite lb, Finite ub) -> ub - lb
_ -> error "Data.IntegerInterval.width: unbounded interval"

-- | How many integers lie within the (bounded) interval.
-- Equal to @Just (width + 1)@ for non-empty, bounded intervals.
-- The @memberCount@ of an unbounded interval is @Nothing@.
memberCount :: IntegerInterval -> Maybe Integer
memberCount x
| null x = Just 0
| otherwise =
case (lowerBound x, upperBound x) of
(Finite lb, Finite ub) -> Just (ub - lb + 1)
_ -> Nothing

-- | pick up an element from the interval if the interval is not empty.
pickup :: IntegerInterval -> Maybe Integer
pickup x =
Expand Down
14 changes: 14 additions & 0 deletions test/TestIntegerInterval.hs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,20 @@ prop_width_singleton =
forAll arbitrary $ \x ->
IntegerInterval.width (IntegerInterval.singleton x) == 0

{--------------------------------------------------------------------
memberCount
--------------------------------------------------------------------}

case_memberCount_null =
IntegerInterval.memberCount IntegerInterval.empty @?= Just 0

case_memberCount_positive =
IntegerInterval.memberCount (0 <=..< 10) @?= Just 10

prop_memberCount_singleton =
forAll arbitrary $ \x ->
IntegerInterval.memberCount (IntegerInterval.singleton x) == Just 1

{--------------------------------------------------------------------
map
--------------------------------------------------------------------}
Expand Down

0 comments on commit 5155346

Please sign in to comment.