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 committed Dec 19, 2023
1 parent 21d7a82 commit bcf20c5
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 interval.
-- Equal to @width + 1@ for non-empty intervals.
-- @memberCount@ of an unbounded interval is @undefined@.
memberCount :: IntegerInterval -> Integer
memberCount x
| null x = 0
| otherwise =
case (lowerBound x, upperBound x) of
(Finite lb, Finite ub) -> ub - lb + 1
_ -> error "Data.IntegerInterval.memberCount: unbounded interval"

-- | 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 @?= 0

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

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

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

0 comments on commit bcf20c5

Please sign in to comment.