[Haskell-cafe] Why does Enum succ and pred functions throw exception
ok at cs.otago.ac.nz
Fri Jun 22 02:36:25 CEST 2012
On 21/06/2012, at 9:11 PM, Rouan van Dalen wrote:
> I was hoping to have some functions like:
> safeSucc :: (Enum a) => a -> Maybe a
Types that are instances of Enum don't necessarily have bounds.
It always struck me as odd that Enum doesn't extend Ord.
There's a reason given for not having Bounded extend Ord,
which doesn't really apply to a class having fromEnum :: a -> Int.
Testing whether an enum bound is at a limit is thus a bit tricky.
isMaxBound, isMinBound :: (Enum t, Bounded t) => t -> Bool
isMaxBound x = fromEnum x == fromEnum (maxBound `asTypeOf` x)
isMinBound x = fromEnum x == fromEnum (minBound `asTypeOf` x)
safeSucc, safePred :: (Enum t, Bounded t) => t -> Maybe t
safeSucc x = if isMaxBound x then Nothing else Just (succ x)
safePred x = if isMinBound x then Nothing else Just (pred x)
More information about the Haskell-Cafe