Skip to content

Commit

Permalink
Merge pull request #17 from tfausak/patch-1
Browse files Browse the repository at this point in the history
Add toBoundedEnum
  • Loading branch information
paf31 authored Aug 17, 2016
2 parents cd4a15e + a604c0a commit 1812314
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Data/Enum.purs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module Data.Enum
, upFrom
, downFrom
, Cardinality(..), runCardinality
, class BoundedEnum, cardinality, toEnum, fromEnum
, class BoundedEnum, cardinality, toEnum, fromEnum, toEnumWithDefaults
, defaultCardinality
, defaultToEnum
, defaultFromEnum
Expand Down Expand Up @@ -242,3 +242,18 @@ defaultToEnum n
-- | Runs in `O(n)` where `n` is `fromEnum a`
defaultFromEnum :: forall a. Enum a => a -> Int
defaultFromEnum = maybe 0 (\prd -> defaultFromEnum prd + 1) <<< pred

-- | Like `toEnum` but returns the first argument if `x` is less than
-- | `fromEnum bottom` and the second argument if `x` is greater than
-- | `fromEnum top`.
-- |
-- | ``` purescript
-- | toEnumWithDefaults False True (-1) -- False
-- | toEnumWithDefaults False True 0 -- False
-- | toEnumWithDefaults False True 1 -- True
-- | toEnumWithDefaults False True 2 -- True
-- | ```
toEnumWithDefaults :: forall a. BoundedEnum a => a -> a -> Int -> a
toEnumWithDefaults b t x = case toEnum x of
Just enum -> enum
Nothing -> if x < fromEnum (bottom :: a) then b else t

0 comments on commit 1812314

Please sign in to comment.