Safe and polymorphic Enum in Haskell

I am trying to write full versions of unsafe functions Enum:

predMay :: Enum a => a -> Maybe a
succMay :: Enum a => a -> Maybe a
toEnumMay :: Enum a => Int -> Maybe a

My problem is that unsafe functions are only partial, if Enumalso Bounded, so safe versions should have a different form in two cases:

predMayUnboundedEnum :: Enum a => a -> Maybe a
predMayUnboundedEnum = Just . pred

predMayBoundedEnum :: (Enum a, Bounded a) => a -> Maybe a
predMayBoundedEnum x
  | fromEnum x == fromEnum (minBound `asTypeOf` x) = Nothing
  | otherwise  = Just (pred x)

The best idea I had to get, I want to use a different model:

class Enum a => SafeEnum a where
  predMay :: a -> Maybe a
instance Enum a => SafeEnum a where
  predMay = predMayUnboundedEnum
instance (Enum a, Bounded a) => SafeEnum a where
  predMay = predMayBoundedEnum

but it causes a complaint to Duplicate instance declarations.

, ? - ? ( prelude-safeenum, Enum , deriving it.) Enum , ?

+4
1

. , Haskell . - , Bounded . , . (, , , , Integer Bounded, . instance Bounded Integer where {minBound = 7; maxBound = 3}, .)

- -. , :

class Enum a => SafeEnum a where
  predMay :: a -> Maybe a
  predMay = predMayUnboundedEnum

instance SafeEnum Integer
instance SafeEnum Rational
instance SafeEnum Int where predMay = predMayBoundedEnum
...
+5

Source: https://habr.com/ru/post/1660501/


All Articles