From a604c0a5b917825b6074c1334219c7474b9e3ff6 Mon Sep 17 00:00:00 2001 From: Taylor Fausak Date: Wed, 27 Jul 2016 11:46:23 -0500 Subject: [PATCH] Add toEnumWithDefaults --- src/Data/Enum.purs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Data/Enum.purs b/src/Data/Enum.purs index d1feac3..bbed64a 100644 --- a/src/Data/Enum.purs +++ b/src/Data/Enum.purs @@ -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 @@ -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